2023年12月7日发(作者:)

HTTPBODY编码问题(中文字符乱码)

Servlet

返回数据的时候,通过

vletOutputStream

获取

ServletOutputStream

返回到前端页面时没有出现乱码

// 打印到浏览器未出现乱码

ServletOutputStream pw = putStream();

(new String("UG中午").getBytes());

();

();

1-1

原因是

new String("UG中午").getBytes()

使用的是系统默认的编码,此时是

GBK

,

es()

的源码如下所示:

static byte[] encode(char[] ca, int off, int len) {

// tCharset()默认读取还是配置的语言编码;也是就是系统的;

String csn = tCharset().name();

try {

// use charset name encode() variant which provides caching.

return encode(csn, ca, off, len);

} catch (UnsupportedEncodingException x) {

warnUnsupportedCharset(csn);

}

try {

return encode("ISO-8859-1", ca, off, len);

} catch (UnsupportedEncodingException x) {

// If this code is hit during VM initialization, MessageUtils is

// the only way we will be able to get any kind of error message.

("ISO-8859-1 charset not available: "

+ ng());

// If we can not find ISO-8859-1 (a required encoding) then things

// are seriously wrong with the installation.

(1);

return null;

}

}

到了浏览器使用的解码也是

GBK

所以是正常的。不过在开发中这里还是建议设置成

UTF-8

.

----------------------------------------

但是使用

PrintWriter

打印时候,出现了乱码,解决办法是加上

tentType("application/json; charset=utf-8");

并且将

racterEncoding(“UTF-8”)

写在

ter()

前面

// 告诉浏览器用UTF-8解码 不加会出现乱码

tentType("application/json; charset=utf-8");

// 这句写上了可能会也没有效果:

// 原因: racterEncoding("UTF-8")语句执行之前执行了ter()语句。

// 所以这句应该写在ter()前面

racterEncoding("UTF-8");

PrintWriter pw1 =ter();

("C中午");

();

();

分析

PrintWriter

出现乱码的原因:当通过

Reponse

返回给客户的时候,这个过程需要先进行编码,再到浏览器进行解码。编码字符集可以通

racterEncoding

来设置,它将会覆盖

racterEncoding

的值,并通过

Header

ContentType

返回到客户端,浏览器接收

到的返回的

Socket

流时将通过

Content-Type

charset

来解码。

默认的优先级从高到底如下:

1.

racterEncoding("UTF-8")

设置编码格式

2.通过

HTTP Header

Content-Type

charset

设置,如果没有进行第二步;

3.通过

HTMLde

中的

charset

来解码

4.如果上面的都未定义,那么浏览器通过默认的编码器解码

1-2 contentType中的charset