使用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");

	}

}

猜你喜欢

转载自blog.csdn.net/qq_36791569/article/details/80379740