我们使用java代码进行接口远程调用第三方接口时,总会抒写接口代码,那么有这么多种方式进行发送请求。那我们应该怎么使用呢?
比如有webservice接口,比如有Post请求的接口,必须有Get请求的接口。比如传的参数有xml的形式,比如传的参数有json格式等等格式情况,那我们的接口请求代码应该如何区别,抒写呢?
我们要根据postMan中的方式来,只要是能够通过postMan发送成功的请求都可以使用
首先是我们的请求方式:
第一点:在postMan的请求方式有:GET、POST、PUT、DELETE请求。
第二点:在PostMan中我们需要传入url链接,那么new HttpGet(url)这里面的url就是链接地址。
GET:HttpGet httpGet =newHttpGet(url);POST:HttpPost method =newHttpPost(url);PUT:HttpPut put =newHttpPut(url);DELETE:HttpDelete delete =newHttpDelete(url);
第三点:在PostMan中我们需要Params的时候:
HttpParams httpParams =newBasicHttpParams();
httpParams.setParameter("","");
httpParams.setParameter("","");
httpParams.setParameter("","");
method.setParams(httpParams);
第四点:在PostMan中我们需要设置Headers,其中方token或者字节编码的时候很使用。
HttpPost method =newHttpPost(url);
method.addHeader("","");
method.addHeader("","");
method.addHeader("","");
第五点:在PostMan中我们需要设置Body,其中需要传入参数,不管是xml还是json都可以。那么我们需要设置两个地方。
1、在第四点中的header中需要设置传入参数的是xml还是json:
method.addHeader("Content-Type","application/json;");这里是json
method.addHeader("Content-Type","application/xml;");这里是xml
2、在传回来的参数中我们需要设置返回的数据类型和字符编码集:param是发送的body参数。
StringEntity entity =newStringEntity(param,"utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json;");
method.setEntity(entity);//放入到method请求中。
第六点:这样进行发送请求:method是集合请求方式,Params,Headers,body参数以后的集合。然后进行发送。
CloseableHttpClient httpClient =HttpClients.createDefault();//得到发送。HttpResponse resultRep = httpClient.execute(method);
第七点:在PostMan中返回的数据,我们需要如下来接收:
/请求发送成功,并得到响应/
if(resultRep.getStatusLine().getStatusCode()==200){String str ="";/**读取服务器返回过来的json字符串数据**/
log.info("=========测试"+resultRep.toString());String str4 =EntityUtils.toString(resultRep.getEntity());
log.info("========str4"+str4);
result = str4;}
举例如下:
第一种方法:
publicstaticStringgetwebserviceNew(String method,String serviceUrl,String user,String pw,String param){try{//第一步:选择请求方式:PostMethod postMethod =null;
postMethod =newPostMethod();
postMethod.setPath(serviceUrl);String auth ="bearer "+pw;//第二步:设置header参数
postMethod.addRequestHeader("Authorization", auth);
postMethod.setRequestHeader("Content-Type","text/xml");//第三步:得到需要发送的bodyString xmlInfo =getXmlInfo(method,user,pw,param);//第四步:设置发送的参数编码集:
postMethod.setRequestEntity(newStringRequestEntity(xmlInfo.toString(),"application/xml","UTF-8"));org.apache.commons.httpclient.HttpClient httpClient =neworg.apache.commons.httpclient.HttpClient();//第五步:发送请求:int response = httpClient.executeMethod(postMethod);// 执行POST方法
log.info("response--接口状态码-->"+response);String result = postMethod.getResponseBodyAsString();
log.info("result-接口返回值-->"+result);return result;}catch(Exception e){
log.info("e----->"+e);//logger.info("请求异常"+e.getMessage(),e);thrownewRuntimeException(e.getMessage());}}privatestaticStringgetXmlInfo(String method,String fydm,String token,String xml){StringBuilder sb =newStringBuilder();
sb.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:szft='http://szft.tdh/'>");
sb.append("<soapenv:Header/>");
sb.append("<soapenv:Body>");
sb.append("<szft:"+method+">");
sb.append("<fydm>"+fydm+"</fydm>");
sb.append("<token>"+token+"</token>");
sb.append("<xml>"+xml+"</xml>");
sb.append("</szft:"+method+">");
sb.append("</soapenv:Body>");
sb.append("</soapenv:Envelope>");return sb.toString();}
第二种方法:
/**
* http请求接口,获取通达海token和获取通达海代理人使用
* post请求
* @param url url地址
* @param param 请求参数
* @param token token
* @param ContentType 发送数据类型
* @return
* @throws IOException
* @throws ClientProtocolException
*/publicstaticStringhttpPostAllAgent(String url,String param,String token,StringContentType)throwsClientProtocolException,IOException{try{TimeUnit.SECONDS.sleep(1);}catch(InterruptedException e){
e.printStackTrace();}
url =URLDecoder.decode(url,"UTF-8");CloseableHttpClient httpClient =HttpClients.createDefault();String result =null;HttpPost method =newHttpPost(url);Map<String,Object> headers =newHashMap<String,Object>();
headers.put("Content-Type",ContentType);
headers.put("Accept-Charset","charset=utf-8");
headers.put("Authorization", token);for(Map.Entry<String,Object> head : headers.entrySet()){
method.addHeader(head.getKey(),String.valueOf(head.getValue()));}//设置请求访问时间RequestConfig requestConfig =RequestConfig.custom().setSocketTimeout(1000*60).setConnectTimeout(1000*60).build();//设置请求和传输超时时间
method.setConfig(requestConfig);if(null!= param){StringEntity entity =newStringEntity(param,"utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType(ContentType);
method.setEntity(entity);}HttpResponse resultRep = httpClient.execute(method);/**请求发送成功,并得到响应**/if(resultRep.getStatusLine().getStatusCode()==200){String str ="";/**读取服务器返回过来的json字符串数据**/
log.info("=========测试"+resultRep.toString());String str4 =EntityUtils.toString(resultRep.getEntity());
log.info("========str4"+str4);
result = str4;}return result;}
multipart/form-data请求方式:
publicstaticStringuploadFile(String url,Map<String,Object> mapData){CloseableHttpClient httpClient =HttpClients.createDefault();String result ="";//每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。String boundary ="----WebKitFormBoundary5ZMULAAn6mngkXzn";try{HttpPost httpPost =newHttpPost(url);//设置请求头
httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);//HttpEntity builderMultipartEntityBuilder builder =MultipartEntityBuilder.create();//字符编码
builder.setCharset(Charset.forName("UTF-8"));//模拟浏览器
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//boundary
builder.setBoundary(boundary);//multipart/form-data// builder.addPart("multipartFile",new FileBody(filePath));// binary// builder.addBinaryBody("name=\"multipartFile\"; filename=\"test.docx\"", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流// //其他参数for(String key : mapData.keySet()){
builder.addTextBody(key, mapData.get(key).toString(),ContentType.create("text/plain",Consts.UTF_8));}//HttpEntityHttpEntity entity = builder.build();
httpPost.setEntity(entity);// 执行提交HttpResponse response = httpClient.execute(httpPost);//响应HttpEntity responseEntity = response.getEntity();if(responseEntity !=null){// 将响应内容转换为字符串
result =EntityUtils.toString(responseEntity,Charset.forName("UTF-8"));}}catch(IOException e){
e.printStackTrace();}catch(Exception e){
e.printStackTrace();}finally{try{
httpClient.close();}catch(IOException e){
e.printStackTrace();}}System.err.println("result"+result);return result;}
版权归原作者 Dubbo-罗 所有, 如有侵权,请联系我们删除。