繁体   English   中英

解压缩GZIP http-response(使用jersey client api,java)

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

有人可以告诉我在从某些Http调用获得响应时解压缩GZIP内容需要做些什么。

要拨打电话我使用Jersey客户端API,请参阅以下代码:

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);

但输出是GZIP,看起来像:

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

如果我能实现以下内容会很好:

  • 能够检测内容是否是GZIP;
  • 如果没有,请在String中正常处理; if,so解压缩并获取String中的内容

只需将GZIPContentEncodingFilter添加到您的客户端:

client.addFilter(new GZIPContentEncodingFilter(false));

不要将响应检索为实体。 将其作为输入流检索并将其包装在java.util.zip.GZIPInputStream中:

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

然后自己读取未压缩的字节并将其转换为String。

另外,检查服务器是否包含HTTP头Content-Encoding: gzip 如果没有,请尝试将其包含在响应中。 也许泽西岛足够聪明,可以做正确的事情。

在Jersey 2.x(我使用2.26):

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

然后getEntity(String.class)往常一样在响应上使用getEntity(String.class)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM