Android: HTTP communication should use "Accept-Encoding: gzip"
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.
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);
}
If you're using API level 8 or above there's AndroidHttpClient.
It has helper methods like:
public static InputStream getUngzippedContent (HttpEntity entity)
and
public static void modifyRequestToAcceptGzipResponse (HttpRequest request)
leading to much more succinct code:
AndroidHttpClient.modifyRequestToAcceptGzipResponse( request );
HttpResponse response = client.execute( request );
InputStream inputStream = AndroidHttpClient.getUngzippedContent( response.getEntity() );