6

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

This page says the following code will setup HttpClient to automatically handle gzip responses (transparent to the user of HttpClient):

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

However, I cannot find the RequestAcceptEncoding and ResponseContentEncoding classes in the Android SDK. Are they just missing -- do I need to write these myself?

Shezan Baig
  • 1,474
  • 1
  • 14
  • 16

2 Answers2

11

Here is the code that I use:

   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;
                   }
               }
           }
       }
   });

You might also want to look at SyncService.java from the Google I/O app.

Dave
  • 6,064
  • 4
  • 31
  • 38
  • Exactly what I needed -- thanks also for the reference to SyncService – Shezan Baig Aug 21 '11 at 16:23
  • 3
    Please remember that if you're using an older version of the Apache HTTP Client you might not find the `GzipDecompressingEntitiy`. You can get that code here: http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore-contrib/src/main/java/org/apache/http/contrib/compress/GzipDecompressingEntity.java – Mridang Agarwalla Sep 11 '12 at 08:52
0

Android is bundled with a rather old version of the Apache HTTP Client library which doesn't have the classes you are missing.

You can bundle a newer version of the Apache HTTP Client library with your application (see this answer) or use AndroidHttpClient instead which was introduced in API level 8.

Community
  • 1
  • 1
Twilite
  • 873
  • 9
  • 22