Edit: I hardcoded the charcter and use repsonse writer to write it, it still comes out to be K�nigsberger
response.setCharacterEncoding("UTF-8"); response.setContentType(contentType); //if(contentType!=null)response.setHeader("Content-Type",contentType); Writer writer = response.getWriter();//new OutputStreamWriter(response.getOutputStream(),"UTF-8"); System.err.println("character encoding is "+response.getCharacterEncoding()); writer.write("Königsberger "); writer.flush();
Edit: I tried setContentType and setContentEncoding prior to calling getWriter(), still no difference in output:
if(res.length()>0){ //pw.write(res); response.setCharacterEncoding("UTF-8"); response.setContentType(contentType); //if(contentType!=null)response.setHeader("Content-Type",contentType); Writer writer = response.getWriter();//new OutputStreamWriter(response.getOutputStream(),"UTF-8"); System.err.println("character encoding is "+response.getCharacterEncoding()); writer.write(res); writer.flush(); }
I am reading some german characters then output them in xml from java servlet, here's how I read them in UTF8:
int len=0; byte[]buffer=new byte[1024]; OutputStream os = sock.getOutputStream(); InputStream is = sock.getInputStream(); query += "\r\n"; os.write(query.getBytes("UTF8"));//iso8859_1")); do{ len = is.read(buffer); if (len>0) { if(outstring==null)outstring=new StringBuffer(); outstring.append(new String(buffer,0,len, "UTF8")); } }while(len>0); System.out.println(outstring);
System.out outputs the string correctly: Königsberger
However when I repipe this string from my servletResponse also using charset=UTF-8 it becomes gobbled: K�nigsberger
private void outputResponse(String res, HttpServletRequest request, HttpServletResponse response) throws IOException { String outputFormat = getOutputFormat(request); String contentType=null; PrintWriter pw = response.getWriter(); //response.setCharacterEncoding("UTF-8"); System.err.println("output "+res); contentType= "text/xml; charset=UTF-8"; res="<?xml version=\"1.0\" encoding=\"utf-8\"?>" + res; if(contentType!=null)response.setHeader("Content-Type",contentType); if(res.length()>0){ pw.write(res); } pw.flush(); }