Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send through ServletOutputStream characters in UTF-8 encoding

My servlet code looks like that:

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 charset of Servlet's outputstream ???

like image 762
GyRo Avatar asked Jan 02 '10 18:01

GyRo


People also ask

How do you encode a response in Java?

The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called. This method may be called repeatedly to change content type and character encoding.


1 Answers

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...); 
like image 90
Brian Agnew Avatar answered Sep 22 '22 11:09

Brian Agnew