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

北城余情 提交于 2019-12-23 09:58:58

问题


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

回答1:


Simply add GZIPContentEncodingFilter to your client:

client.addFilter(new GZIPContentEncodingFilter(false));



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7546783/uncompress-gzip-http-response-using-jersey-client-api-java

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