7

Could someone tell me what I need to do in order to uncompress a GZIP content when getting the response from some Http-call.

To make the call I use the Jersey Client API, see code below:

String baseURI = "http://api.stackoverflow.com/1.1/answers/7539863?body=true&comments=false";
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource wr = client.resource(baseURI); 
ClientResponse response = null;
response = wr.get(ClientResponse.class);
String response_data = response.getEntity(String.class);

System.out.println(response_data);

However the output is GZIP’d and looks like:

{J?J??t??`$?@??????....

It would be good if I could implement the following:

  • being able to detect whether content is GZIP’d or not;
  • If not, process like normal in a String; if, so uncompress and get the content in String
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Larry
  • 11,439
  • 15
  • 61
  • 84
  • For Jersey 2.0 see http://stackoverflow.com/questions/17834028/what-is-the-jersey-2-0-equivalent-of-gzipcontentencodingfilter – Paul Bellora Oct 24 '16 at 13:45

3 Answers3

15

Simply add GZIPContentEncodingFilter to your client:

client.addFilter(new GZIPContentEncodingFilter(false));
Martin Matula
  • 7,969
  • 1
  • 31
  • 35
3

Don't retrieve the response as an entity. Retrieve it as an input stream and wrap it in a java.util.zip.GZIPInputStream:

GZipInputStream is = new GZipInputStream(response.getEntityInputStream());

Then read the uncompressed bytes yourself and turn it into a String.

Also, check whether the server is including the HTTP header Content-Encoding: gzip. If not, try including it in the response. Perhaps Jersey is smart enough to do the right thing.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 1
    thanks, but what if the content is not-GZIPed (i.e. could I implement a way to detect this, depending on the response received?) – Larry Sep 25 '11 at 16:39
  • If you can depend on the server to behave properly, you can check the Content-Encoding value. (Alternatively, the response might just set a mime type of application/x-gzip.) Use `response.getHeaders()` and test for the appropriate values. The only other thing I can think of is that if it seems to be garbage under one assumption, try the other. – Ted Hopp Sep 25 '11 at 19:32
1

In Jersey 2.x (I use 2.26):

WebTarget target = ...
target.register(GZipEncoder.class);

Then getEntity(String.class) can be used on the response as usual.

Vikas
  • 1,900
  • 1
  • 19
  • 20