httpClient傳送get和post引數形式總結
阿新 • • 發佈:2019-02-19
最近工作中接觸到httpClient類,於是簡單總結了下,發現形式並不複雜:
這裡對於get請求形式,比較簡單,只需要把引數加到地址上,一起執行即可
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); try { httpclient.start(); HttpGet request = new HttpGet(url + "?" + param); Future<HttpResponse> future = httpclient.execute(request, null); HttpResponse response = future.get();
對於post傳送引數的形式就比較多樣了,但是儲存的位置都是在請求的body中:
通過HttpPost可以設定各種傳輸的格式,有好多好多種,但是總結起來最常用的包含以下三種:
可以通過HttpPost物件的setHeader屬性來設定:
形式如:
HttpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
其中Content-Type代表傳送的資料的格式,後面的引數可以根據需要設定,最常用到的如下:
application/json : JSON資料格式
application/xml : XML資料格式(被JSON替代了)
application/x-www-form-urlencoded :<form encType=””>中預設的encType,form表單資料被編碼為key/value格式傳送到伺服器(表單預設的提交資料的格式)
1:以form形式傳送引數
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestLogConfig);
if (parasMap != null && parasMap.size() > 0) {
List<NameValuePair> parasList = new ArrayList<NameValuePair>();
Iterator<String> keys = parasMap.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
parasList.add(new BasicNameValuePair(key, parasMap.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(parasList, "UTF-8"));
這裡以form傳送最關鍵的地方在於這個方法:httpPost.setEntity(new UrlEncodedFormEntity(parasList, "UTF-8"));
而下面的JSON則直接可以通過setEntity賦值即可
2:以json形式傳送引數
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
String jsonStr = JSON.toJSONString(parasMap);
if (parasMap != null && parasMap.size() > 0) {
StringEntity strEntity = new StringEntity(URLEncoder.encode(
jsonStr, "UTF-8"));
// StringEntity strEntity = new StringEntity(jsonStr);
httpPost.setEntity(strEntity);
}
try {
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity entity = response.getEntity();