servlet gzip 中文乱码

来源:互联网 发布:淘宝买演唱会门票 编辑:程序博客网 时间:2024/06/06 04:02

本人编码格式一律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();}