使用GZIPInputStream解压缩REST响应

3

我正在尝试解压REST服务返回的gzip压缩响应:

Content-Encoding=[gzip], Content-Type=[application/json], Content-Length=[710] ...

我正在使用Grails REST客户端构建器插件:

def response = new RestBuilder().get(HOST + "/api/..."){
        contentType "application/json"
        accept "application/json"
}       

返回的响应是Spring的ResponseEntity。我正在尝试使用GZIPInputStream解压缩数据:

String body = response.getBody()        
new GZIPInputStream(new ByteArrayInputStream(body.getBytes())).text

这导致了Caused by ZipException: Not in GZIP format

很明显我做错了什么,但我不知道是什么。欢迎任何建议。


这与我的另一个问题有关,链接在此处:https://stackoverflow.com/questions/28157605/decompression-of-gziped-response-grails-groovy。 - john
println body 显示什么?我怀疑你试图解压缩两次。 - tim_yates
@tim_yates 的 println body 显示的是一些乱码,类似于 ?Mo?0??J?3?b?_?8T?4?... 但其中还有其他不允许出现在此处的字符。我的理解是它仍然被压缩了。 - john
你能否尝试在你的闭包中添加 contentEncoding = ContentEncoding.Type.GZIP - tim_yates
@tim_yates contentEncoding 不是一个受支持的参数。会抛出异常"No signature method ...contentEncoding()"。 - john
显示剩余2条评论
2个回答

4
如果您确实需要继续使用Rest客户端构建器,只需稍微修改您的客户端代码即可:
def response = new RestBuilder().get(HOST + "/api/..."){
    contentType "application/json"
    accept byte[].class, "application/json" }

注意accept调用中的额外参数 - byte [].class - 这表示RestTemplate应该避免对响应进行任何解析。

要解压缩,现在可以执行以下操作:

new GZIPInputStream(new ByteArrayInputStream(response.body))

是的,我知道,已经用 accept 回答了,但如果切换 Rest 组件不是一个选项,一些人可能仍然会发现它有帮助。


谢谢 - 很棒的答案。 - john

3

我之前一直无法在grails / groovy库中让其正常运行,因此我转向使用spring和httpcomponents:

HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build());
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

ResponseEntity<String> response = restTemplate.exchange(
            "some/url/", HttpMethod.GET, new HttpEntity<Object>(requestHeaders),
            String.class);

自动解压缩gzip,因此不再需要手动解压缩。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接