演示gzip压缩响应正文数据
2015-09-05 17:47
375 查看
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 MyServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte b[] = data.getBytes();
System.out.println("原始数据的大小:" + b.length);
// GZIP压缩
// 创建一个带有缓存的内存输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(out);
gout.write(b);
gout.close();
// 输出压缩到缓冲流中的数据(响应正文)
b = out.toByteArray();
System.out.println("压缩后的数据大小:" + b.length);
// 通知客户端数据的压缩编码
response.setHeader("Content-Encoding", "gzip");
// 通知客户端响应正文的数据大小,静态页面响应速度快
response.setHeader("Content-Length", b.length+"");
response.getOutputStream().write(b);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
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 MyServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte b[] = data.getBytes();
System.out.println("原始数据的大小:" + b.length);
// GZIP压缩
// 创建一个带有缓存的内存输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(out);
gout.write(b);
gout.close();
// 输出压缩到缓冲流中的数据(响应正文)
b = out.toByteArray();
System.out.println("压缩后的数据大小:" + b.length);
// 通知客户端数据的压缩编码
response.setHeader("Content-Encoding", "gzip");
// 通知客户端响应正文的数据大小,静态页面响应速度快
response.setHeader("Content-Length", b.length+"");
response.getOutputStream().write(b);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
相关文章推荐
- CodeForces 48C D - The Race (Fraction,数学)
- 使用 Lua 编写一个 Nginx 认证模块 - 技术翻译 - 开源中国社区
- win7 iis7 ftp配置
- 函数模板与模板函数
- Centos7 安装ELK
- python编程题:汉诺塔排序
- 【年度总结】一个程序员的自我修养
- 将html页改成jsp的两种方式
- 安卓学习笔记---Activity
- 论文写作和修改的技巧
- Hibernate 异常:object references an unsaved transient instance - save the transient instance before fl
- Android 控件之五:CheckBox 选择框
- 转载 Memcached BinaryProtocol incr指令内存泄露的bug
- SDWebImage使用方法
- javascript里为什么不能把</script>放到字符串里
- 巧妇能为少米之炊(3)——压缩饼干(ZRAM)
- 初识网络游戏防作弊
- A list of base boxes for Vagrant - Vagrantbox.es
- 构建squid透明代理网关
- linux运维实战练习-2015年9月5日课程作业(练习)安排