ServletOutputStream回写页面乱码

一段utf-16的string,整了好多种格式,硬是无法正确输出到页面上:

 

首先尝试了outputstream, 即便指定string-》byte[]的编码,还是出错

 

resp.getOutputStream().write(out.getBytes("UTF-16"));
resp.getOutputStream().print(out);
resp.getOutputStream().flush();
resp.getWriter().close(); 

然后尝试过Printwriter,均以失败告终。

 

 

借此也搞明白了response回写内容的两个方法:(指上面的writer和outStream)

1.PrintWriter object that can send character text to the client.

2.ServletOutputStream suitable for writing binary data in the response

3.Calling flush() on the xxx  commits the response.

4.Either getOutputStream() or getWriter() may be called to write the body, not both.

 

但是比较诡异的是,为什么这两种方式(指上面的writer和outStream)会出现乱码呢?

再看看编码解析的过程:

uses the character encoding returned by getCharacterEncoding().

  首先使用response对象的getCharacterEncoding(),如果没有设置,则默认编码方式都为ISO-8859-1

 

那么问题也就明确了,在输入流指定正确的编码之后,还需要配合response的编码参数,否则读出来解析就乱码

 

正解

//方式1
resp.setCharacterEncoding("UTF-16");
resp.getWriter().print(out);
resp.getWriter().flush();
resp.getOutputStream().close();

//方式2
resp.setCharacterEncoding("UTF-16");
resp.getOutputStream().write(out.getBytes("UTF-16"));
resp.getOutputStream().flush();
resp.getOutputStream().close();

 

 再或者,包装一层: 

 

ServletOutputStream out2 = resp.getOutputStream(); 
OutputStreamWriter ow = new OutputStreamWriter(out2,"UTF-16"); 
ow.write(out); 
ow.flush(); 
ow.close(); 

 

 

你可能感兴趣的:(技术点滴)