最近使用Apache的httpclient发起httpPost请求,后端一直提示编码格式错误。代码和环境都是在UTF-8写处理的,后端接受的编码也是UTF-8,但是后端依然报错。在跟踪代码的时候,发现主要是客户端StringEntity的处理问题。StringEntity设置编码格式主要有以下两种方式
//第一种方式:后端无法解码
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params));
stringEntity.setContentType("UTF-8");
//第二种方式:请求成功
StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(params), "UTF-8");
在跟踪源码的时候,发现StringEntity的处理逻辑如下:
public StringEntity(String string) throws UnsupportedEncodingException {
this(string, ContentType.DEFAULT_TEXT);
}
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());
}
}
当不传入ContentType时,会使用默认值,而该处的默认编码格式是:ISO_5598_1。所以后端才会提示异常。
总结:使用httpclient时,尽量使用第二种方式来初始化StringEntity,避免因为编码格式导致异常。