要点:
1.new一个GZIPOutputStream,而GZIPOutputStream里面需要包一个流,最好是包一个内存流ByteArrayOutputStream,因为内存流不需要知道长度而且其长度可以变化。
2.输出压缩数据时,必须设置响应头
resp.setHeader(“Content-Encoding”, “gzip” );
public class GzipServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
String str="dklkewi湖南城市学院湖南城市学院湖南城市学院湖南城市学院湖南城市学院湖南城市学院w224242424242424444444444422424241dfdfdffddffdfdds244224242424242424444444444422424241dfdfdffiow湖南城市学院esdkkewwe,m";
byte src[] = str.getBytes("UTF-8");
System.out.println("压缩前的长度:"+src.length);
ByteArrayOutputStream bout = new ByteArrayOutputStream();//内存流
GZIPOutputStream gzipOut = new GZIPOutputStream( bout );
gzipOut.write(src);//把src压缩到 bout中
gzipOut.close();//刷缓存
byte dest[] = bout.toByteArray();//把源数据src压缩成目标数据dest
System.out.println("压缩后的长度:"+dest.length);
resp.setContentType("text/html;charset=utf-8");
//输出压缩数据时,必须设置响应头
resp.setHeader("Content-Encoding", "gzip" );
OutputStream out = resp.getOutputStream();
out.write(dest);
}
}
注意:若需要压缩的str长度太短可能会出现压缩后的长度大于压缩前的长度这种情况,这是因为压缩本身需要消耗,只有需压缩的str够长才能体现
压缩的作用。