What header should be used for sending GZIP compre

2019-01-22 12:39发布

问题:

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?

回答1:

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



回答2:

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.