使用Gzip压缩数据,加快页面访问速度

             在返回的json数据量大时,启用Gzip压缩,可以提高传输效率。下面为Gzip压缩对json字符串压缩并输出到页面的代码。

一、代码

	/** 向浏览器输出字符串响应数据,启用gzip压缩 */ 
	protected void writeResponseDataStr(String data){
		/** 获取响应对象 */
		HttpServletResponse response = ServletActionContext.getResponse();
		/** 设置响应内容类型 */
		response.setContentType("text/html;charset=utf-8");
		try {
			/** 告诉浏览器,服务器响应的数据是用GZIP压缩的 */
			response.setHeader("Content-Encoding", "gzip");
			//GZIP压缩的原理是:将数据全部压缩进内存输出流中,再从将内存输出流中的数据输出
			/** 创建内存输出流的容器 */
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			/** 创建GZIP压缩对象 */
			GZIPOutputStream gzip = new GZIPOutputStream(bos);
			/** 进行压缩 */
			gzip.write(data.getBytes("utf-8"));
			gzip.flush();
			gzip.close();
			/** 向浏览器输出响应数据 */
			response.getOutputStream().write(bos.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
	};

原文地址:https://www.cnblogs.com/zeng1994/p/7447555.html