服务器使用Gzip压缩数据,加快网络传输(Java 例子)

在我们的项目中,添加对gzip的支持,是为了加快数据在网络中的传输速度。


使用gzip,首先要设置请求消息头Accept-Encoding为gzip。这样,你将会得到一个响应,根据消息头Content-Encoding为gzip你可以知道,传输过来的数据是经过gzip压缩的。另外,消息头Content-Length会告诉你压缩后的数据长度。

用Java实现的gzip
  1. GetMethodmethod=newGetMethod(url);//生成一个get方法实例
  2. method.setQueryString(queryString);//设置查询字符串
  3. method.addRequestHeader("Accept-Encoding","gzip");//设置接受响应消息为gzip
  4. HttpClientclient=newHttpClient();//生成执行get方法的客户端实例
  5. client.executeMethod(method);//执行get方法
  6. InputStreamin=method.getResponseBodyAsStream();//获取响应消息体
  7. HeadercontentEncoding=method.getResponseHeader("Content-Encoding");//获取消息头Content-Encoding判断数据流是否gzip压缩过
  8. if(contentEncoding!=null&&contentEncoding.getValue().equalsIgnoreCase("gzip")){
  9. GZIPInputStreamgzipIn=newGZIPInputStream(in);
  10. intlen=Integer.parseInt(method.getResponseHeader("Content-Length").getValue());
  11. byte[]b=newbyte[len];
  12. gzipIn.read(b);
  13. Stringjson=newString(b);
  14. System.out.println(json);
  15. }

使用gzip在服务器端压缩数据的例子。

  1. byte[]result=data.getBytes("UTF-8");
  2. if(response.getHeader("Accept-Encoding").equalsIgnoreCase("gzip"))
  3. {
  4. //System.out.println("Beforecompression,thedatasizeis:"+result.length);
  5. //Usinggzipcompressthedata
  6. ByteArrayOutputStreamout=newByteArrayOutputStream();
  7. GZIPOutputStreamgout=newGZIPOutputStream(out);
  8. gout.write(json.getBytes("UTF-8"));
  9. gout.close();
  10. result=out.toByteArray();
  11. //System.out.println("Aftercompression,thedatasizeis"+gzipResult.length);
  12. this.getResp().setHeader("Content-Encoding","gzip");
  13. this.getResp().setHeader("Content-Length",result.length+"");
  14. }
  15. response.getOutputStream().write(result);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值