servlet gzip 中文乱码

本人编码格式一律UTF-8

但是,在使用Gzip压缩后的xml中文总是乱码,以下是解决方法:

关键在于getBytes的时候,指定编码

resp.setHeader("Cache-Control","no-cache");		
resp.setContentType("text/xml; charset=UTF-8");
String backxml = "<root>中文</root>";
resp.setCharacterEncoding("UTF-8");
String encoding=req.getHeader("Accept-Encoding");		
if (encoding!=null && encoding.indexOf("gzip")>=0) {  // gzip broswer?
    resp.setHeader("Content-Encoding","gzip");
    OutputStream o=resp.getOutputStream();
    GZIPOutputStream gz=new GZIPOutputStream(o);
    gz.write(backxml.getBytes("UTF-8"));
    gz.finish();
    gz.close();
    o.close();
} else {  //	
    PrintWriter o = resp.getWriter();
    o.println(backxml);
    o.flush();
    o.close();
}	



你可能感兴趣的:(xml,String,servlet,null,encoding)