昨天一篇GZIP相关实现引起大家的广泛关注,为一位朋友验证一下浏览器对gzip的支持情况,才有此文!
相关链接: GZIP本身就是一种网络流压缩算法,而且应用相当广泛。如果网络访问过程中,其数据流较大,势必降低网络访问效率,此时就需要考虑使用压缩!当然,在浏览器与服务器的交互中,要考虑浏览器是否支持这些算法,以及服务器运行压缩所带来的负载。如果你关注浏览器上传的“Accept-Encoding”属性,你就能看明白这一点。 GZIP如何压缩,我这里就不废话了,不清楚的朋友请关注() 至于如何使得服务器支持gzip的流输出,关键点只有一行代码:- response.setHeader("Content-Encoding", "gzip");
- /**
- * 2010-4-14
- */
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.util.zip.GZIPOutputStream;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * GZip服务
- *
- * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>
- * @since 1.0
- */
- public class GZipServlet extends HttpServlet {
- private static final long serialVersionUID = -4811926975427533081L;
- private static final String ENCODING = "UTF-8";
- /**
- * 压缩
- *
- * @param data
- *
- * @throws Exception
- */
- private byte[] compress(byte[] data) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- // 压缩
- GZIPOutputStream gos = new GZIPOutputStream(baos);
- gos.write(data, 0, data.length);
- gos.finish();
- byte[] output = baos.toByteArray();
- baos.flush();
- baos.close();
- return output;
- }
- /**
- * @param request
- * @param response
- * @throws ServletException
- * @throws IOException
- */
- private void excute(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- byte[] data = "我是一个中国人!".getBytes(ENCODING);
- try {
- byte[] output = compress(data);
- // 设置Content-Encoding,这是关键点!
- response.setHeader("Content-Encoding", "gzip");
- // 设置字符集
- response.setCharacterEncoding(ENCODING);
- // 设定输出流中内容长度
- response.setContentLength(output.length);
- OutputStream out = response.getOutputStream();
- out.write(output);
- out.flush();
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- excute(request, response);
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- excute(request, response);
- }
- }
- <Connector
- port="8080"
- protocol="HTTP/1.1"
- connectionTimeout="20000"
- redirectPort="443"
- URIEncoding="UTF-8"
- compression="on"
- noCompressionUserAgents="gozilla, traviata"
- compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain,application/json"
- />
- response.setContentType("text/plain;charset=utf-8");
http://snowolf.iteye.com/blog/643443