apache.httpClient遇到的编码问题
使用httpclient跨系统进行接口交互时发现,对方系统收到的报文中的中文字符都变成了“??”,明明我系统中使用的编码是UTF-8,从前端发过来的数据也是能正常显示,正常打印到日志的,为啥发过去就别成了乱码?
http请求处理的代码是用的apache的httpClient,代码是从网上直接拿来用的,然后就定位到StringEntity部分的代码:
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params));
stringEntity.setContentType("UTF-8");
这部分代码第一眼好像是没啥问题,其实里面有个巨坑;
我们看下StringEntity源码中的构造函数
public StringEntity(String string, ContentType contentType) throws UnsupportedCharsetException {
Args.notNull(string, "Source string");
Charset charset = contentType != null ? contentType.getCharset() : null;
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
this.content = string.getBytes(charset);
if (contentType != null) {
this.setContentType(contentType.toString());
}
}
可以看到,在new StringEntity的时候,已经将String用默认的ISO_8859_1转换成了[]byte了,所以,在这个过程中存在字符串的破坏,因为这个默认的ISO_8859_1编码是不支持中文的! (至于为什么说字符串会再转码的时候被破坏请看上一篇我写的文章)
所以,正确的方式应该是:
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), "UTF-8");
这样才能保证你传过去的编码是UTF-8