Cookie压缩

  Cookie在HTTP的头部,所以通常的gzip和deflate针对HTTP Body的压缩不能压缩Cookie,如果Cookie的量非常大,则可以考虑将Cookie也做压缩,压缩方式是将Cookie的多个k/v对看成普通的文本,做文本压缩。压缩算法同样可以使用gzip和deflate算法,但是需要注意的一点是,根据Cookie的规范,在Cookie中不能包含控制字符,仅能包含ASCII码为34~126的可见字符。所以压缩后的结果再进行转码,可以进行Base32或者Base64编码。

  可以配置一个Filter在页面输出时对Cookie进行全部或者部分压缩:

    /**
     * 用DeflaterOutputStream对Cookie进行压缩
     * @param c
     * @param response
     */
    private void compressCookie(Cookie c,HttpServletResponse response){
        ByteArrayOutputStream bos = null;
        DeflaterOutputStream dos = null;
        try {
            bos = new ByteArrayOutputStream();
            dos = new DeflaterOutputStream(bos);
            dos.write(c.getValue().getBytes());
            dos.close();
            System.out.println("压缩之前:"+c.getValue().getBytes().length);
            String compress = new sun.misc.BASE64Encoder().encode(bos.toByteArray());
            response.addCookie(new Cookie("compress",compress));
            System.out.println("压缩之后:"+compress.getBytes().length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

解压:

    /**
     * InflaterInputStream解压
     * @param c
     */
    private void unCompressCookie(Cookie c){
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] compress = new sun.misc.BASE64Decoder().decodeBuffer(new String(c.getValue().getBytes()));
            ByteArrayInputStream bis = new ByteArrayInputStream(compress);
            InflaterInputStream inflater = new InflaterInputStream(bis);
            byte[] b = new byte[1024];
            int count;
            while((count = inflater.read(b)) >= 0){
                out.write(b,0,count);
            }
            inflater.close();
            System.out.println(out.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

posted @ 2017-02-17 11:26  刘尊礼  阅读(518)  评论(0)    收藏  举报