欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

在Android系统中使用gzip进行数据传递实例代码

程序员文章站 2023-11-04 14:37:04
接下来,让我解说一下如何在android系统中使用gzip进行数据传递 http协议上的gzip编码是一种用来改进web应用程序性能的技术。大流量的web站点常常使用gzi...
接下来,让我解说一下如何在android系统中使用gzip进行数据传递
http协议上的gzip编码是一种用来改进web应用程序性能的技术。大流量的web站点常常使用gzip压缩技术来减少文件大小,减少文件大小有两个明显的好处,一是可以减少存储空间,二是通过网络传输文件时,可以减少传输的时间。作者在写这篇博客时经过测试,4.4mb的文本数据经过gzip传输到客户端之后变为392kb,压缩效率极高。

一.服务端
服务端有2种方式去压缩,一种可以自己压缩,但是更推荐第二种方式,用printwriter作为输出流,工具类代码如下
复制代码 代码如下:

/**
* 判断浏览器是否支持 gzip 压缩
* @param req
* @return boolean 值
*/
public static boolean isgzipsupport(httpservletrequest req) {
string headencoding = req.getheader("accept-encoding");
if (headencoding == null || (headencoding.indexof("gzip") == -1)) { // 客户端 不支持 gzip
return false;
} else { // 支持 gzip 压缩
return true;
}
}
/**
* 创建 以 gzip 格式 输出的 printwriter 对象,如果浏览器不支持 gzip 格式,则创建普通的 printwriter 对象,
* @param req
* @param resp
* @return
* @throws ioexception
*/
public static printwriter creategzippw(httpservletrequest req, httpservletresponse resp) throws ioexception {
printwriter pw = null;
if (isgzipsupport(req)) { // 支持 gzip 压缩
pw = new printwriter(new gzipoutputstream(resp.getoutputstream()));
// 在 header 中设置返回类型为 gzip
resp.setheader("content-encoding", "gzip");
} else { // // 客户端 不支持 gzip
pw = resp.getwriter();
}
return pw;
}

servlet代码如下:
复制代码 代码如下:

public void dopost(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
response.setcharacterencoding("utf-8");
response.setheader("content-encoding", "gzip");
string ret = "{\"contentlayer\":{\"title\":\"内容层\"},\"pagelink\":{\"title\":\"页面跳转\"},\"webbrowser\":{\"title\":\"浏览器\"},"
+ "\"inlinepage\":{\"title\":\"内嵌页面\"},\"videocomp\":{\"title\":\"视频\"},"
+ "\"popbutton\":{\"title\":\"内容开关\"},\"zoomingpic\":{\"title\":\"缩放大图\"},"
+ "\"rotate360\":{\"title\":\"360度旋转\"}}";
printwriter pw = new printwriter(new gzipoutputstream(response.getoutputstream()));
pw.write(ret);
pw.close();
}
public void doget(httpservletrequest request, httpservletresponse response)
throws servletexception, ioexception {
this.dopost(request, response);
}

在代理软件中跟踪到的数据如下:
复制代码 代码如下:

‹«vrîï+ií+ñi¬l-r²ªv*é,éiu²r:rëäým•ju”ós}2ó²‘e/m>üììë«@òá©ineùåå¨úŸ¬?pàøw¼g^nf^*ètóo™r–™'šïœŸ[€¬àôåc[áöç8•–”äç¡»nÿª7@
¢òós3óò2“‘uœþºýè–ïg÷€tå—$–¤› +r·¸ðä‡zh¤†ˆ

实际数据如下:
复制代码 代码如下:

{"contentlayer":{"title":"内容层"},"pagelink":{"title":"页面跳转"},"webbrowser":{"title":"浏览器"},"inlinepage":{"title":"内嵌页面"},"videocomp":{"title":"视频"},"popbutton":{"title":"内容开关"},"zoomingpic":{"title":"缩放大图"},"rotate360":{"title":"360度旋转"}}