在Android中自动处理gzip http响应

She*_*aig 6 android gzip http

参考:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/httpagent.html#d4e1261

此页面说明以下代码将设置HttpClient为自动处理gzip响应(对用户透明HttpClient):

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.addRequestInterceptor(new RequestAcceptEncoding());
httpclient.addResponseInterceptor(new ResponseContentEncoding());
Run Code Online (Sandbox Code Playgroud)

但是,我在Android SDK中找不到RequestAcceptEncodingResponseContentEncoding类.他们只是缺少 - 我需要自己写这些吗?

Dav*_*ave 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;
                   }
               }
           }
       }
   });
Run Code Online (Sandbox Code Playgroud)

您可能还想查看Google I/O应用程序中的SyncService.java.

  • 请记住,如果您使用的是旧版本的Apache HTTP Client,则可能找不到`GzipDecompressingEntitiy`.您可以在此处获取该代码:http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/GzipDecompressingEntity.java (3认同)