使用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();
		}
	};
 
1
    /** 向浏览器输出字符串响应数据,启用gzip压缩 */ 
2
    protected void writeResponseDataStr(String data){
3
        /** 获取响应对象 */
4
        HttpServletResponse response = ServletActionContext.getResponse();
5
        /** 设置响应内容类型 */
6
        response.setContentType("text/html;charset=utf-8");
7
        try {
8
            /** 告诉浏览器,服务器响应的数据是用GZIP压缩的 */
9
            response.setHeader("Content-Encoding", "gzip");
10
            //GZIP压缩的原理是:将数据全部压缩进内存输出流中,再从将内存输出流中的数据输出
11
            /** 创建内存输出流的容器 */
12
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
13
            /** 创建GZIP压缩对象 */
14
            GZIPOutputStream gzip = new GZIPOutputStream(bos);
15
            /** 进行压缩 */
16
            gzip.write(data.getBytes("utf-8"));
17
            gzip.flush();
18
            gzip.close();
19
            /** 向浏览器输出响应数据 */
20
            response.getOutputStream().write(bos.toByteArray());
21
        } catch (IOException e) {
22
            e.printStackTrace();
23
        }
24
    };

转载于:https://www.cnblogs.com/zeng1994/p/7447555.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值