最近工作中接触到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();