gzip压缩
程序员文章站
2022-03-12 18:53:27
...
/**
* 判断客户端是否支持GZIP或者需要GZIP格式的数据
* @param req
* @return
*/
private boolean isGzipSupported(HttpServletRequest req) {
String browserEncodings = req.getHeader("Accept-Encoding");
return (browserEncodings != null) && (browserEncodings.indexOf("gzip") != -1);
}
//
PrintWriter pw=null;
//
GZIPOutputStream out = null;
ByteArrayInputStream in=null;
try {
if (isGzipSupported(request)) { // 支持 gzip 压缩
long b=System.currentTimeMillis();
response.setHeader("content-encoding", "gzip");
// pw = new PrintWriter(new GZIPOutputStream(response.getOutputStream()));
out = new GZIPOutputStream(response.getOutputStream());
in = new ByteArrayInputStream(postData.getBytes(charSet));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
MapLog.debug(Catalog.getLocalizationForKey("LogDebugDataCompressionTime",resourceName)+":"+((System.currentTimeMillis()-b)/1000.00)+"秒");
} else { // // 客户端 不支持 gzip
pw = response.getWriter();
pw.print(postData);
pw.close();
}
} catch (IOException e) {
}finally{
if(pw!=null){
pw.close();
}
if(in!=null){
in.close();
}
if(out!=null){
out.finish();
out.close();
}
}