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();
}	



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章