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

时间:2011-09-25 16:15:26

标签: java jersey gzip jersey-1.0

有人可以告诉我在从某个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 uncompress并获取String
  • 中的内容

3 个答案:

答案 0 :(得分:13)

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

client.addFilter(new GZIPContentEncodingFilter(false));

答案 1 :(得分:3)

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

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

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

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

答案 2 :(得分:0)

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

WindowsFormsHost host = new WindowsFormsHost();
host.Child = grid; //this is instance of WF control
testwindow.testSurface.Children.Add(host); // add in Window(WPF)

然后可以像往常一样在响应中使用WebTarget target = ... target.register(GZipEncoder.class);