2011-08-21 83 views
6

參考:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/httpagent.html#d4e1261自動處理中的Android gzip的HTTP響應

本頁面說下面的代碼將設置HttpClient自動處理gzip的響應(透明的HttpClient用戶):

DefaultHttpClient httpclient = new DefaultHttpClient(); 
httpclient.addRequestInterceptor(new RequestAcceptEncoding()); 
httpclient.addResponseInterceptor(new ResponseContentEncoding()); 

然而,我在Android SDK中找不到RequestAcceptEncodingResponseContentEncoding類。他們是否錯過了 - 我是否需要自己寫這些?

回答

11

這裏是我使用的代碼:

mHttpClient.addResponseInterceptor(new HttpResponseInterceptor() { 
     public void process(final HttpResponse response, 
       final HttpContext context) throws HttpException, 
       IOException { 
      HttpEntity entity = response.getEntity(); 
      Header encheader = entity.getContentEncoding(); 
      if (encheader != null) { 
       HeaderElement[] codecs = encheader.getElements(); 
       for (int i = 0; i < codecs.length; i++) { 
        if (codecs[i].getName().equalsIgnoreCase("gzip")) { 
         response.setEntity(new GzipDecompressingEntity(
           entity)); 
         return; 
        } 
       } 
      } 
     } 
    }); 

你也可能想看看SyncService.java從谷歌I/O的應用程序。

+0

正是我需要的 - 感謝也爲參考到SyncService –

+0

鏈接不起作用。請糾正它。 –

+3

請記住,如果您使用的是舊版本的Apache HTTP客戶端,則可能找不到'GzipDecompressingEntitiy'。您可以在此處獲取該代碼:http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/GzipDecompressingEntity.java –

0

Android捆綁了一個相當舊版本的Apache HTTP Client庫,它沒有缺少的類。

你可以捆綁在Apache HTTP客戶端庫的較新版本與您的應用程序(見this答案),或使用AndroidHttpClient代替這是在API層面推出8

+0

_此級別在API級別22中已棄用._ – Prince