此接口调用主要是针对于JSON格式的传参,http协议的通讯(此方法讲解的是POST访问方式),以下是对接口调用的一些理解 ,以便后续学习,如下分为2个部分:1、调用的主方法; 2、封装的工具类首先,调用的主要方法由于接口地址URL是通过构造方法进行赋值,在方法中就不需要传参了,调用主要方法中需传入接口所需参数,并转换成JSON格式的字符串,再传入到工具类进行处理调用(工具类往下翻)
public String test(String a, String b) throws Exception {
String url ="地址";
Map<String, String> params = new HashMap<>();
Map<String, Map<String, String>> requestMap = new HashMap<>();
params.put("a", a);
params.put("b", b);
requestMap.put("Request", params);
HttpPost httpPost = null;
try {
String json = JsonUtil.writeValueAsString(requestMap);
httpPost = HttpRequest.getHttpPost(url, json);
return HttpRequest.getHttpPostRequest(httpPost);
} catch (Throwable e) {
throw new Exception();
}
}
其次,工具类:
工具类一,此工具类需要传入接口地址和接口所需要的参数,并设置传输格式、字符集,并将参数与URL地址组合,返回一个HttpPost的请求方式:
public static HttpPost getHttpPost(String url,String json){
StringEntity requestEntity = new StringEntity(json, Charset.forName("utf-8"));
requestEntity.setContentType("application/json");
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(requestEntity);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
return httpPost;
}
工具类二,此工具类是针对上面返回HttpPost进行处理,传入HttpPost ,并创建CloseableHttpClient httpclient对象,
由httpclient 进行execute(httpPost)方法,传入httpPost进行调用访问
:
public static String getHttpPostRequest(HttpPost httpPost) {
CloseableHttpClient httpclient = HttpClients.createDefault();
//请求超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(30*1000)
.setConnectionRequestTimeout(30*1000)
.setSocketTimeout(30*1000)
.build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
StatusLine status = null;
int statuscode = 0;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String msg = new String(EntityUtils.toString(entity, "utf-8"));
return msg;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
status = response.getStatusLine();
statuscode = status.getStatusCode();
if (statuscode != HttpStatus.SC_OK) { //状态码200表示连接成功
if(httpPost != null)
httpPost.abort();
}
}
return "";
}