直接上代碼
public static String doPostJson(String url, String json) {
// 創(chuàng)建Httpclient對(duì)象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請(qǐng)求
HttpPost httpPost = new HttpPost(url);
// 創(chuàng)建請(qǐng)求內(nèi)容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
// 將內(nèi)容放請(qǐng)求對(duì)象中
httpPost.setEntity(entity);
// 執(zhí)行http請(qǐng)求
response = httpClient.execute(httpPost);
if(response != null && response.getEntity() != null) {
//設(shè)置響應(yīng)返回的編碼格式及轉(zhuǎn)字符串
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
}else{
resultString = null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(response != null) {
response.close();
}
} catch (IOException e) {
logger.error("http請(qǐng)求失敗:", e);
}
}
return resultString;
}