34

This question is extension to the question here. I am using the code here reproduced below to GZIP compress a JSONObject.

String foo = "value";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;

try {
    gzos = new GZIPOutputStream(baos);
    gzos.write(foo.getBytes("UTF-8"));
} finally {
    if (gzos != null) try { gzos.close(); } catch (IOException ignore) {};
}

byte[] fooGzippedBytes = baos.toByteArray();

I am using a DefaultHttpClient to send this compressed JSONObject to server(the code is in my control).

My Question

What header should I use in my request? I am using request.setHeader("Content-type", "application/json"); for sending JSON to server?

Community
  • 1
  • 1
Gaurav Agarwal
  • 18,754
  • 29
  • 105
  • 166

3 Answers3

48

To inform the server that you are sending gzip-encoded data, send the Content-Encoding header, not Accept-Encoding.

pevik
  • 4,523
  • 3
  • 33
  • 44
Michael Hampton
  • 9,737
  • 4
  • 55
  • 96
  • If you wonder also how to specify that the json text is UTF-8: set the content type to `application/json; charset=utf-8` – David S. Jul 14 '20 at 11:47
21

This answer shows you that you need to set a header indicating that you are sending data compressed:

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

The answer also shows how to deal with the incoming compressed data.

Community
  • 1
  • 1
Audrius
  • 2,836
  • 1
  • 26
  • 35
  • Sorry @Audrius, I hope you will appreciate Michael Hampton stand more merit, therefore I am accepting it in greater good of community. – Gaurav Agarwal Jul 11 '12 at 09:36
5
  • Content-Type:application/json - tells what type of content data in the http call
  • Content-Encoding: gzip - tells what compression being used.

application/json or text/xml or other type can be compressed as gzip and sending to receiver and with Content-Type header only, receiver will identify the incoming data is of type json/xml/text and then convert back to object of type json/xml/text.

With Content-Encoding header only receiver will identify the incoming data is getting gzip compressed. Then receiver required to decompress the incoming data and use it.

Calos
  • 1,783
  • 19
  • 28
Jagadeesan M
  • 51
  • 1
  • 2