package cn.itcast.web;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data ="aaaaaaaaaaaaaaaaaaa";
System.out.println("原始数据大小:"+data.getBytes().length);
ByteArrayOutputStream bout =new ByteArrayOutputStream(); //缓冲流
GZIPOutputStream gout =new GZIPOutputStream(bout); //压缩流
gout.write(data.getBytes()); //获取到数据自动压缩,压缩到缓冲流中
gout.close();//压缩流一关就会进入到缓冲流中
byte gzip[] =bout.toByteArray(); //得到压缩后的数据
System.out.println("压缩后的数据大小:"+gzip.length);
//通知浏览器数据采用的压缩格式(设置Http响应中的消息头)
response.setHeader("Content-Encoding", "gzip");
//通知浏览器回送压缩后数据的长度(设置Http响应中的消息头)
response.setHeader("Content-Length",gzip.length+"");
response.getOutputStream().write(gzip);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}