Http协议(页面内容压缩)

要点:
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够长才能体现
压缩的作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值