2011-08-21 81 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