Uncompress http-response GZIP (using jersey client api, java)

Can someone tell me what I need to do to unzip the GZIP content when I receive a response from some Http call.

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

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 of GZIPd is as follows:

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

It would be nice if I could implement the following:

  • the ability to determine whether the content is GZIPd or not;
  • If not, execute the procedure as normal in String; if, so uncompress and get the contents in String
+5
source share
3 answers

Just add the GZIPContentEncodingFilter to your client:

client.addFilter(new GZIPContentEncodingFilter(false));
+13

. java.util.zip.GZIPInputStream:

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

.

, HTTP- Content-Encoding: gzip. , . , , .

+3

In Jersey 2.x (I use 2.26):

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

Then getEntity(String.class)you can use for the answer as usual.

0
source

All Articles