我们使用java代码进行接口远程调用第三方接口时,总会抒写接口代码,那么有这么多种方式进行发送请求。那我们应该怎么使用呢? 比如有webservice接口,比如有Post请求的接口,必须有Get请求的接口。比如传的参数有xml的形式,比如传的参数有json格式等等格式情况,那我们的接口请求代码应该如何区别,抒写呢?
我们要根据postMan中的方式来,只要是能够通过postMan发送成功的请求都可以使用 首先是我们的请求方式: 第一点:在postMan的请求方式有:GET、POST、PUT、DELETE请求。 第二点:在PostMan中我们需要传入url链接,那么new HttpGet(url)这里面的url就是链接地址。
GET:HttpGet httpGet = new HttpGet(url);
POST:HttpPost method = new HttpPost(url);
PUT:HttpPut put = new HttpPut(url);
DELETE:HttpDelete delete = new HttpDelete(url);
第三点:在PostMan中我们需要Params的时候:
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("","");
httpParams.setParameter("","");
httpParams.setParameter("","");
method.setParams(httpParams);
第四点:在PostMan中我们需要设置Headers,其中方token或者字节编码的时候很使用。
HttpPost method = new HttpPost(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 = new StringEntity(param, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json;");
method.setEntity(entity);
第六点:这样进行发送请求:method是集合请求方式,Params,Headers,body参数以后的集合。然后进行发送。
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse resultRep = httpClient.execute(method);
第七点:在PostMan中返回的数据,我们需要如下来接收: /请求发送成功,并得到响应/
if (resultRep.getStatusLine().getStatusCode() == 200) {
String str = "";
log.info("=========测试"+resultRep.toString());
String str4 = EntityUtils.toString(resultRep.getEntity());
log.info("========str4"+str4);
result = str4;
}
举例如下: 第一种方法:
public static String getwebserviceNew(String method,String serviceUrl,String user,String pw,String param){
try {
PostMethod postMethod = null;
postMethod = new PostMethod();
postMethod.setPath(serviceUrl);
String auth = "bearer "+pw;
postMethod.addRequestHeader("Authorization", auth);
postMethod.setRequestHeader("Content-Type", "text/xml") ;
String xmlInfo = getXmlInfo(method,user,pw,param);
postMethod.setRequestEntity(new StringRequestEntity(xmlInfo.toString(),"application/xml","UTF-8"));
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
int response = httpClient.executeMethod(postMethod);
log.info("response--接口状态码-->"+response);
String result = postMethod.getResponseBodyAsString() ;
log.info("result-接口返回值-->"+result);
return result;
} catch (Exception e) {
log.info("e----->"+e);
throw new RuntimeException(e.getMessage());
}
}
private static String getXmlInfo(String method,String fydm,String token,String xml) {
StringBuilder sb = new StringBuilder();
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();
}
第二种方法:
public static String httpPostAllAgent(String url,String param,String token,String ContentType) throws ClientProtocolException, 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 = new HttpPost(url);
Map<String, Object> headers = new HashMap<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 = new StringEntity(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 = "";
log.info("=========测试"+resultRep.toString());
String str4 = EntityUtils.toString(resultRep.getEntity());
log.info("========str4"+str4);
result = str4;
}
return result;
}
|