zoukankan      html  css  js  c++  java
  • 使用GZIP压缩网页内容(一)

    在JDK中提供了GZIP压缩,来压缩网页的内容,降低网络传输时候的字节数,到达浏览器端的时候,再解压,GZIP压缩之后传输耗费的流量大大降低,但是同时也不会降低用户体验。

    package day04;
    
    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;
    /**
     * @author mzy
     */
    public class ContentServlet extends HttpServlet {
    
    	private static final long serialVersionUID = 3505039773816640152L;
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		response.setContentType("text/html;charset=utf-8");
    		// 准备内容
    		StringBuffer sb = new StringBuffer();
    		for (int i=1; i<=3000; i++) {
    			sb.append("abcd");
    		}
    		System.out.println("压缩前的数据大小:"+sb.toString().getBytes().length);
    		// 输出到浏览器
    		// response.getWriter().write(sb.toString());
    		
    		/*
    		 * 对网页内容进行gzip格式进行压缩
    		 * 
    		 * 使用ByteArrayOutputStream作为缓存
    		 * 直接有个toByteArray方法!
    		 * 
    		 * 压缩前:12000B
    		 * 压缩后:51B
    		 */
    		// 1) 创建一个临时缓存容器
    		ByteArrayOutputStream buf = new ByteArrayOutputStream();
    		// 2) 创建GZIPOutputStream
    		GZIPOutputStream gzip = new GZIPOutputStream(buf);
    		// 3) 进行压缩
    		gzip.write(sb.toString().getBytes());
    		// 4) 调用结束方法,把缓存内容刷新
    		gzip.finish();
    		// 5) 得到压缩后的内容
    		byte[] result = buf.toByteArray();
    		System.out.println("压缩后的数据大小:"+result.length);
    		
    		// 因为压缩成了字节,所以不能使用Writer了
    		// 必须使用outputStream了
    		response.getOutputStream().write(result);
    		
    		/*
    		 * 告诉浏览器,是通过GZIP压缩过的内容;
    		 * 不然没有办法正常解析。
    		 * 		通过响应头!
    		 */
    		response.setHeader("content-encoding", "gzip");
    		
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8");
    		response.setContentType("text/html;charset=utf-8");
    
    	}
    
    }
    


  • 相关阅读:
    git命令使用方法
    git与svn对比
    浏览器缓存原理
    网络性能优化常用方法
    sass/scss 和 less的区别
    AngularJS和ReactJS对比
    让IE6,7,8支持HTML5新标签的方法
    Retina 屏移动设备 1px解决方案
    HttpClient学习
    国家二字码对照表
  • 原文地址:https://www.cnblogs.com/mzywucai/p/11053414.html
Copyright © 2011-2022 走看看