1. 程式人生 > >HttpClient post請求 傳送Json資料

HttpClient post請求 傳送Json資料

import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public void requestToBaiDu() {

//傳送請求的URL

String url = “http://www.baidu.com”;

//編碼格式

String charset = “UTF-8”;

//請求內容

String content = “{“date”:“2017-11-06 18:27:10.0”,“sum”:”-3400",“complainOdrNbr”:“null”}";
//使用幫助類HttpClients建立CloseableHttpClient物件.

CloseableHttpClient client = HttpClients.createDefault();

//HTTP請求型別建立HttpPost例項

HttpPost post = new HttpPost(url);

//使用addHeader方法新增請求頭部,諸如User-Agent, Accept-Encoding等引數.

post.setHeader(“Content-Type”, “application/json;charset=UTF-8”);

//組織資料
StringEntity se = new StringEntity(content );

//設定編碼格式

se.setContentEncoding(charset);

//設定資料型別

se.setContentType(“application/json”);

//對於POST請求,把請求體填充進HttpPost實體.

post.setEntity(se);

//通過執行HttpPost請求獲取CloseableHttpResponse例項 ,從此CloseableHttpResponse例項中獲取狀態碼,錯誤資訊,以及響應頁面等等.

CloseableHttpResponse response = client.execute(post);

//通過HttpResponse介面的getEntity方法返回響應資訊,並進行相應的處理

HttpEntity entity = response.getEntity();

String resData = EntityUtils.toString(response.getEntity());

//最後關閉HttpClient資源.

httpClient.close()

}

作者:暖寶寶吧
來源:CSDN
原文:https://blog.csdn.net/qq_31911463/article/details/78480991
版權宣告:本文為博主原創文章,轉載請附上博文連結!