httpclient之json乱码

本文解析了JSON消息体中出现中文乱码的原因及解决方法,强调Content-Encoding与StringEntity的区别,指导如何正确设置编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 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;否则将会在消息体中出现中文乱码。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值