Alex Rivera | Logout

How to Compress a JSONObject send it over Http in Android?

Asked 2012-07-09T20:44:04.227
8

I am sending a JSONObject to my Webserver from an Android client using the code from this example. Reproducing code here

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
    postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);

My Question

How to do best compression on JSONObject before sending it to server and how to decompress it on Server (I am using Java Servlets)?

Edit
Report

1 Answer

14

According to this http://android-developers.blogspot.com/2011/09/androids-http-clients.html If you are using Gingerbread or later HttpURLConnection automatically adds gzip compression:

In Gingerbread, we added transparent response compression. HttpURLConnection will automatically add this header to outgoing requests, and handle the corresponding response:

Accept-Encoding: gzip

Your webserver would then need to handle gzip compression.

Edit:
Serve Gzipped content with Java Servlets

Edit 2:
Gzip compression using DefaultHttpClient Enabling GZip compression with HttpClient

private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";

final DefaultHttpClient client = new DefaultHttpClient(manager, parameters);

client.addRequestInterceptor(new HttpRequestInterceptor() {
  public void process(HttpRequest request, HttpContext context) {
    // Add header to accept gzip content
    if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
      request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
    }
  }
});

client.addResponseInterceptor(new HttpResponseInterceptor() {
  public void process(HttpResponse response, HttpContext context) {
    // Inflate any responses compressed with gzip
    final HttpEntity entity = response.getEntity();
    final Header encoding = entity.getContentEncoding();
    if (encoding != null) {
      for (HeaderElement element : encoding.getElements()) {
        if (element.getName().equalsIgnoreCase(ENCODING_GZIP)
answered 2012-07-09T20:50:42.433

Your Answer