【问题标题】:Uncompress GZIP http-response (using jersey client api, java)解压 GZIP http-response (使用 jersey client api, java)
【发布时间】:2011-09-25 16:15:25
【问题描述】:

有人能告诉我在从一些 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 压缩;
  • 如果不是,则在字符串中正常处理;如果,那么解压缩并获取字符串中的内容

【问题讨论】:

标签: java jersey gzip jersey-1.0


【解决方案1】:

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

client.addFilter(new GZIPContentEncodingFilter(false));

【讨论】:

    【解决方案2】:

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

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

    然后自己读取解压后的字节,转成String。

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

    【讨论】:

    • 谢谢,但如果内容不是 GZIPed 怎么办(即,我可以根据收到的响应实施一种检测方法吗?)
    • 如果您可以依赖服务器正常运行,您可以检查 Content-Encoding 值。 (或者,响应可能只设置应用程序/x-gzip 的 mime 类型。)使用response.getHeaders() 并测试适当的值。我唯一能想到的另一件事是,如果在一个假设下它似乎是垃圾,请尝试另一个。
    【解决方案3】:

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

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

    然后getEntity(String.class)可以照常用于响应。

    【讨论】:

    • 2.x 客户端中没有getEntity(Class) 方法。有一个readEntity(Class) 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多