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 "";
}