How to send UTF-8 encoded ServletOutputStream characters

My servlet code is as follows:

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

...

then I get the error:

 java.io.CharConversionException: Not an ISO 8859-1 character: ืฉ javax.servlet.ServletOutputStream.print(ServletOutputStream.java:89) javax.servlet.ServletOutputStream.println(ServletOutputStream.java:242) rtm.servlets.CampaignLogicServlet.doPost(CampaignLogicServlet.java:68) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 

How can I switch the encoding of the servlet output stream ???

+46
java internationalization servlets utf-8
Jan 02 '09 at 18:42
source share
5 answers

I think you want to use getWriter () instead. This will take a string and encode it, while the output stream is designed to process binary data.

From the doc:

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

This method or getOutputStream () can be called to write the body, not both.

Here's the code change:

 response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println(...MY-UTF-8 CODE...); 
+87
Jan 02 '09 at 18:45
source share

This also works:

 ServletOutputStream out = response.getOutputStream(); out.write("MY-UTF-8 CODE".getBytes("UTF-8")); 
+8
Feb 01 '14 at 22:54
source share

The same case happened to me before, and I tried to add one line on top of PrintWriter, and it works.

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

+3
Nov 08 '13 at 18:59
source share
 public void output(String jsonStr, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8;"); response.setCharacterEncoding("UTF-8"); ServletOutputStream out = response.getOutputStream(); out.write(jsonStr.getBytes("UTF-8")); out.flush(); out.close(); } 
+1
Jun 08 '17 at 11:38 on
source share
 // HTML Output code list StringBuffer select_code = new StringBuffer(); List<con_element> ccc = codeService.code_select(code); for(int i=0;i<ccc.size();i++){ select_code.append("<option value='" + ccc.get(i).getCce_num() + "'>" + ccc.get(i).getCce_hname() + "</option>" ); } response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().print( select_code ); 
0
Dec 14 '18 at 2:53
source share



All Articles