关于HttpClient的学习心得,请求参数中文乱码问题

最近调用了一个第三方接口,接口文档限定是 HTTPS post 请求 参数是 json格式。然后随便在网上找了一份HttpClient的工具代码,然后直接调用post的请求,参数也觉得没有问题,返回值也正常,但是后来发现参数中的中文全部变成了问号传递过去了,后来发现是参数传递时编码没有指定,现记录下来以供以后学习查看,有遇到和我一样问题的初学者可以减少差询问题的时间。

代码如下:

  HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
HttpResponse response = null;
try {
     
     httpClient=new DefaultHttpClient();//1创建httpclient对象
     httpPost = new HttpPost(url);//2因为是post请求所以创建httppost对象
        httpPost.addHeader("Content-Type", "application/json");//3设置请求头参数和参数类型
StringEntity se = new StringEntity(jsonstr,"UTF-8");//4设置参数内容,并制定编码格式(之前问题就在这里缺少了 “UTF-8”这个参数,就出现问号了)
se.setContentType("text/json");//设置格式类型
se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
httpPost.setEntity(se);//参数封装到post中
response = httpClient.execute(httpPost);//执行请求方法,返回response响应参数
if (response.getEntity()!=null){//判断响应是否为空
result = EntityUtils.toString(response.getEntity(), charset);//指定响应参数编码然后返回
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}


后续和第三方的技术人员要了一个他们公司的demo,研究学习了一下,发现他们使用的是PoolingHttpClientConnectionManager用了连接池
查了资料才知道,频繁的创建连接(三次握手)断开连接(四次挥手)会消耗很对资源,所以使用连接池技术方便下次调用。

public static void init() {//demo中的初始化方法,其中设置了相关的请求参数和连接数

connMgr = new PoolingHttpClientConnectionManager();

connMgr.setMaxTotal(500);//设置整个连接池最大连接数 根据自己的场景决定
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

RequestConfig.Builder configBuilder = RequestConfig.custom();

configBuilder.setConnectTimeout(1000);//设置最大连接数

configBuilder.setSocketTimeout(1000);//设置服务端连接超时

configBuilder.setConnectionRequestTimeout(2000);//设置请求连接超时

configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();

}

//加载初始化配置信息,获取一个httpclient的连接对象

CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig)
.setRetryHandler(httpRequestRetryHandler).build();

 剩下的代码都一样了,get,post 参数自定。
posted @ 2017-12-04 11:56  会游泳的金毛  阅读(5253)  评论(0编辑  收藏  举报