httpclient 4.3.x 版本 post 中文乱码问题

最近使用 httpclient 4.3.x 版本模拟浏览器提交请求,一直没出问题,直到查询数据库,发现了中文乱码。如下是出现问题的代码:

<span style="font-size:18px;">private void cancelOrder(CloseableHttpClient clientQingsong, String qingsongOrderId) throws Exception {
	String url = baseUrl+"/order/cancel";
	RequestBuilder requestBuilder = RequestBuilder.post().setUri(new URI(url));
	requestBuilder.addParameter("order_id", qingsongOrderId);
	CloseableHttpResponse response = clientQingsong.execute(requestBuilder.build());
	
	if(200 != response.getStatusLine().getStatusCode()) {
		throw new Exception("网络异常: "+response.getStatusLine());
	}
	
	String result = EntityUtils.toString(response.getEntity(), "UTF-8");
	JSONObject jsonObject = JSON.parseObject(result);
	if(!"200".equals(jsonObject.getString("status"))) {
		throw new Exception("取消订单失败,原因:"+jsonObject.getString("message"));
	}
}</span>

这个是原始的请求,一直没有出错,其他的更新内容的方法,也是参考此方法的实现,结果发现中文乱码,

由此分析,该方法,如果传输中文的话,也会出现中文乱码,

网上 http://sb122k.iteye.com/blog/1584395 版主的博文,给了我参考,在httpclient传输的过程中,要显式设定字符编码,而如下方式设置字符编码,不起作用;

<span style="font-size:18px;">RequestBuilder requestBuilder = RequestBuilder.post().setUri(new URI(url));
requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");</span>

只能通过httpclient 提供的 HttpEntity 接口来实现字符编码的设定,方法之一如下:

<span style="font-size:18px;">List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("remark", b2bOrder.getRemark())); //备注
RequestBuilder requestBuilder = RequestBuilder.post().setUri(new URI(url));
requestBuilder.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
CloseableHttpResponse response = clientQingsong.execute(requestBuilder.build());
if(200 == response.getStatusLine().getStatusCode()) {
	String result = EntityUtils.toString(response.getEntity(), "UTF-8");
}</span>

换句话说,之前的用法,本身就是错误的,只是碰巧没有遇到中文而已!






你可能感兴趣的:(httpclient,中文,乱码,post,4)