***1.实现代码:***
public void getPostMethod(String url){
Map<String, Object> map = new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
Map<String, Object> result = new HashMap<>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
HttpResponse response = httpClient.execute(httpPost);
if (null == response || response.getStatusLine() == null) {
throw new Exception("Post Request For Url[{}] is not ok. Response is null");
} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new Exception("Post Request For Url[{}] is not ok. Response Status Code is {}");
}
String resultString = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = JSONObject.parseObject(resultString);
if (jsonObj.getInteger("STATUS") == 6) {
result.put("STATUS", "success");
result.put("FILEID", jsonObj.getInteger("FILEID"));
} else {
result.put("STATUS", "failed");
}
result.put("MESSAGE", jsonObj.getString("MSG"));
return result;
}
2.POM.xml需要添加的依赖:
org.apache.httpcomponents
httpclient
4.4
org.apache.httpcomponents
httpmime
4.4
***时间:2020-10-29***