原文地址:https://blog.csdn.net/qq_26975307/article/details/82713725
/**
* 發送post請求
* @param url 路徑
* @param jsonObject 參數(json類型)
* @param encoding 編碼格式
* @return
* @throws ParseException
* @throws IOException
*/
public static String send(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{
String body = "";
//創建httpclient對象
CloseableHttpClient client = HttpClients.createDefault();
//創建post方式請求對象
HttpPost httpPost = new HttpPost(url);
//裝填參數
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//設置參數到請求對象中
httpPost.setEntity(s);
System.out.println("請求地址:"+url);
// System.out.println("請求參數:"+nvps.toString());
//設置header信息
//指定報文頭【Content-type】、【User-Agent】
// httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//執行請求操作,並拿到結果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//獲取結果實體
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定編碼轉換結果實體為String類型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//釋放鏈接
response.close();
return body;
}