天天看點

Android 解析gzip格式資料

啟用GZIP:

啟用GZIP通信需要伺服器和用戶端雙方的支援。

在用戶端方面,進行HTTP請求時,要在HTTP的header處添加:

[plain]  view plain copy

  1. Accept-Encoding: gzip,deflate  

如果伺服器支援,則在傳回資料包的header中會包含:

[plain]  view plain copy

  1. Accept-Encoding: gzip,deflate  

解壓GZIP:

下面将使用代碼的方式表示解壓GZIP的方法,下面這個函數使用了get方法擷取網絡上的資料,擷取後使用GZIPinputStream類對GZIP資料進行了解壓。并傳回了得到的字元串:

[java]  view plain copy

  1. public String get(String url){  
  2.     HttpGet get=new HttpGet(url);  
  3.     HttpClient client=new DefaultHttpClient();  
  4.     get.addHeader("accept-encoding","gzip, deflate");  
  5.     //在標頭中添加gzip格式  
  6.     HttpResponse response=null;  
  7.     ByteArrayBuffer bt= new ByteArrayBuffer(4096);  
  8.     String resultString="";  
  9.     try{  
  10.         response=client.execute(get);  
  11.         //執行Get方法     
  12.         HttpEntity he = response.getEntity();  
  13.         //以下是解壓縮的過程  
  14.         GZIPInputStream gis = new GZIPInputStream(he.getContent());  
  15.         int l;  
  16.         byte[] tmp = new byte[4096];  
  17.         while ((l=gis.read(tmp))!=-1){  
  18.             bt.append(tmp, 0, l);  
  19.         }  
  20.         resultString = new String(bt.toByteArray(),"utf-8");   
  21.         //後面的參數換成網站的編碼一般來說都是UTF-8  
  22.     }  
  23.     catch(Exception e)  
  24.     {  
  25.         Log.i("ERR",e.toString()); //抛出進行中的異常  
  26.     }  
  27.     return resultString;  
  28. }