啟用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;
- }