启用GZIP:
启用GZIP通信需要服务器和客户端双方的支持。
在客户端方面,进行HTTP请求时,要在HTTP的header处添加:
[plain] view plain copy
- Accept-Encoding: gzip,deflate
如果服务器支持,则在返回数据包的header中会包含:
[plain] view plain copy
- Accept-Encoding: gzip,deflate
解压GZIP:
下面将使用代码的方式表示解压GZIP的方法,下面这个函数使用了get方法获取网络上的数据,获取后使用GZIPinputStream类对GZIP数据进行了解压。并返回了得到的字符串:
[java] view plain copy
- public String get(String url){
- HttpGet get=new HttpGet(url);
- HttpClient client=new DefaultHttpClient();
- get.addHeader("accept-encoding","gzip, deflate");
- //在包头中添加gzip格式
- HttpResponse response=null;
- ByteArrayBuffer bt= new ByteArrayBuffer(4096);
- String resultString="";
- try{
- response=client.execute(get);
- //执行Get方法
- HttpEntity he = response.getEntity();
- //以下是解压缩的过程
- GZIPInputStream gis = new GZIPInputStream(he.getContent());
- int l;
- byte[] tmp = new byte[4096];
- while ((l=gis.read(tmp))!=-1){
- bt.append(tmp, 0, l);
- }
- resultString = new String(bt.toByteArray(),"utf-8");
- //后面的参数换成网站的编码一般来说都是UTF-8
- }
- catch(Exception e)
- {
- Log.i("ERR",e.toString()); //抛出处理中的异常
- }
- return resultString;
- }