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

一世执手 提交于 2019-11-29 00:07:27
CraigTeegarden

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)) {
          response.setEntity(new InflatingEntity(response.getEntity()));
          break;
        }
      }
    }
  }
});

Edit 3:
Here is another Stackoverflow question regarding the gzipping of post contents GZip POST request with HTTPClient in Java. You will need to manually gzip the data before posting it, since the normal http/gzip operation is the server sending gzipped content to the client.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!