网站压缩数据 GZIP

 1 //1、被压缩数据
 2             String str="Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好Hello 你好";
 3             //2、获得被压缩数据的字节码
 4             byte[] bytes=str.getBytes("utf-8");
 5             //3、声明一个输出流容器
 6             ByteArrayOutputStream byteout=new ByteArrayOutputStream();
 7             //4、声明压缩工具流,并设置压缩目的
 8             GZIPOutputStream zip=new GZIPOutputStream(byteout);
 9             //5、写入数据
10             zip.write(bytes);
11             //6、关闭工具(如果不关闭,不能写入)
12             zip.close();
13             
14             System.out.println("压缩前:"+str.length());
15             //7、压缩以后的字节码
16             byte[] descbyte= byteout.toByteArray();
17             System.out.println("压缩后:"+descbyte.length);
18             //8、设置编码
19             response.setContentType("text/html;charset=utf-8");
20             //9、通知浏览器这是压缩,要求解码显示(必须)
21             response.setHeader("Content-encoding", "gzip");
22             //10、通知浏览器压缩字节长度(非必须)
23             response.setContentLength(descbyte.length);
24             //11、必须使用字节流输出信息
25             OutputStream out=response.getOutputStream();
26             //12、写入
27             out.write(descbyte);

 

posted @ 2014-11-27 20:18  liuwt365  阅读(197)  评论(0编辑  收藏  举报