how to send through ServletOutputStream characters in UTF-8 encoding how to send through ServletOutputStream characters in UTF-8 encoding java java

how to send through ServletOutputStream characters in UTF-8 encoding


I think you want to use getWriter() instead. That will accept a string and encode it, whereas the output stream is for handling binary data.

From the doc:

Returns a PrintWriter object that can send character text to the client. The character encoding used is the one specified in the charset= property of the setContentType(java.lang.String) method, which must be called before calling this method for the charset to take effect.

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

Here's the change of the code:

response.setContentType("text/html; charset=UTF-8");response.setCharacterEncoding("UTF-8");PrintWriter out = response.getWriter();out.println(...MY-UTF-8 CODE...);


This also works:

ServletOutputStream out = response.getOutputStream();out.write("MY-UTF-8 CODE".getBytes("UTF-8")); 


The same case happen to me before and i tried to add-on one line on top of the PrintWriter and it is work.

response.setContentType("text/html; charset=GBK");
PrintWriter out = response.getWriter();