代码改变世界

服务器将数据以压缩的形式,返回给浏览器

2015-08-14 18:41  怡红院丿无痕  阅读(410)  评论(0编辑  收藏  举报

servlet的实现

//压缩输出
public class ServletDemo2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String data = "aaaaaaaa";
        
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        GZIPOutputStream gout = new GZIPOutputStream(bout);
        gout.write(data.getBytes());
        gout.close();
        
        
        byte gzip[] = bout.toByteArray();
        response.setHeader("content-encoding", "gzip");
        response.setHeader("content-length", gzip.length + "");
        
        response.getOutputStream().write(gzip);
        
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}