views:

1892

answers:

4

I've a HTTP communication to a webserver requesting JSON data. I'd like compress this data stream with Content-Encoding: gzip. Is there a way I can set Accept-Encoding: gzip in my HttpClient? The search for gzip in the Android References doesn't show up anything related to HTTP, as you can see here.

A: 

I haven't used GZip, but I would assume that you should use the input stream from your HttpURLConnection or HttpResponse as GZIPInputStream, and not some specific other class.

Dimitar Dimitrov
+13  A: 

You should use http headers to indicate a connection can accept gzip encoded data, e.g:

HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// ...
httpClient.execute(request);

Check response for content encoding:

InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
    instream = new GZIPInputStream(instream);
}
Bakhtiyor
That is a great and very helpful answer with all the details I needed. Thanks a lot.One comment: instead of addHeader I used setHeader. From what I understand this overwrites the existing "Accept-Encoding" if there is one. Not sure which approach is the right/better one. To overwrite an existing header to make sure it has the right value, or to add it in case that there can be other Accept-Encoding headers in parallel.
znq
A: 

Hi, great that there is a way to use GZIP but can you give a complete example this would be a great thing. Now i use just the Webview and the loadURL method. Is it also eays possible to integrate the GZIP way there ?

Bakhtiyor has already given a detailed answer.
znq
A: 

Bakhtiyor's solution works perfect, thank you.

Related Jira (new feature request in v3.*) https://issues.apache.org/jira/browse/HTTPCLIENT-816

adn37