/**
* Specifies the Content-Encoding header, as a string.
* The default implementation calls
* {@link #setContentEncoding(Header) setContentEncoding(Header)}.
*
* @param ceString the new Content-Encoding header, or
* {@code null} to unset
*/
public void setContentEncoding(final String ceString) {
Header h = null;
if (ceString != null) {
h = new BasicHeader(HTTP.CONTENT_ENCODING, ceString);
}
setContentEncoding(h);
}
以上代码json 内容设置关键代码如上有绿色和红色加粗两部分,而绿色部分是正确的,能将中文编码正确,而红色部分在绿色部分不设置编码方式则会编译成乱码。
出现这种问题一般都是将contentEncoding理解为请求时的消息内容编码所致,然而这个编码设置并不是请求时编码设置,所以会出现json串中中文乱码的出现。
浏览器发送请求时,通过 Accept-Encoding 带上自己支持的内容编码格式列表;服务端从中挑选一种用来对正文进行编码,并通过 Content-Encoding 响应头指明选定的格式;浏览器拿到响应正文后,依据 Content-Encoding 进行解压。当然,服务端也可以返回未压缩的正文,但这种情况不允许返回 Content-Encoding。这个过程就是 HTTP 的内容编码机制。
ContentEncoding()源码如下:
/**
* Specifies the Content-Encoding header, as a string.
* The default implementation calls
* {@link #setContentEncoding(Header) setContentEncoding(Header)}.
*
* @param ceString the new Content-Encoding header, or
* {@code null} to unset
*/
public void setContentEncoding(final String ceString) {
Header h = null;
if (ceString != null) {
h = new BasicHeader(HTTP.CONTENT_ENCODING, ceString);
}
setContentEncoding(h);
}
StringEntity()源码如下:
/**
* Creates a StringEntity with the specified content and charset. The MIME type defaults
* to "text/plain".
*
* @param string content to be used. Not {@code null}.
* @param charset character set to be used. May be {@code null}, in which case the default
* is {@link HTTP#DEF_CONTENT_CHARSET} is assumed
*
* @throws IllegalArgumentException if the string parameter is null
* @throws UnsupportedCharsetException Thrown when the named charset is not available in
* this instance of the Java virtual machine
*/
public StringEntity(final String string, final String charset)
throws UnsupportedCharsetException {
this(string, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), charset));
}
从上代码可以看出,这是两种完全不同的编码设置。所以当请求的json中有中文时,应当在将其转换为对应消息体new StringEntity()的时候设置对应的编码方式,其默认的编码格式DEF_CONTENT_CHARSET = ISO-8859-1;否则将会在消息体中出现中文乱码。