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>

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






  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值