首页 > 解决方案 > 如何在空手道中解压缩 gzip 响应

问题描述

有没有办法用空手道解压缩 gzip 响应?我曾尝试使用 karate-apache v0.9.6 和 karate-jersey v0.9.6,但默认情况下两者都没有解压响应内容。当我尝试获取并打印响应时,我看到了这样的结果。

INFO  com.intuit.karate - [print] the resp   l�ǒ�@�Ee�{��wh�5�Bk-�����ͪ͘�T  

我不确定我在这里缺少什么。

但是当我尝试使用 apache httpclient.GzipDecompressingEntity 时,我设法将响应实体解压缩为字符串并按预期工作。 final String s1 = IOUtils.toString(gzipDecompressingEntity.getContent(), StandardCharsets.UTF_8);

我也提到了这个问题,但没有运气。

这是空手道输出:

与泽西岛

1 > GET http://localhost:4000/somedata?type=json&gzip=yes
1 > Accept-Encoding: deflate
1 > User-Agent: Jersey/2.30 (HttpUrlConnection 11.0.9)

[ForkJoinPool-1-worker-3] DEBUG com.intuit.karate - response time in milliseconds: 139.51
1 < 200
1 < Cache-control: no-cache
1 < Connection: keep-alive
1 < Content-Disposition: attachment; filename="somedata.gz"
1 < Content-Length: 78056
1 < Content-Type: application/gzip
1 < Keep-Alive: timeout=5

[ForkJoinPool-1-worker-3] INFO  com.intuit.karate - [print] the resp       
l�ǒ�@�Ee�{��wh�5�Bk-�����ͪ͘�T   �~�Ɋ�iʴ(�?������巵us���a,�]n^�jz=a�gU��!

使用 Apache Httpclient

1 > GET http://localhost:4000/somedata?type=json&gzip=yes
1 > Accept-Encoding: deflate
1 > Connection: Keep-Alive
1 > User-Agent: Apache-HttpClient/4.5.12 (Java/11.0.9)

17:26:14.243 [ForkJoinPool-1-worker-3] DEBUG com.intuit.karate - response time in milliseconds: 102.86
1 < 200
1 < Cache-control: no-cache
1 < Connection: keep-alive
1 < Content-Disposition: attachment; filename="somedata.gz"
1 < Content-Length: 78065
1 < Content-Type: application/gzip
1 < Keep-Alive: timeout=5

 [ForkJoinPool-1-worker-3] INFO  com.intuit.karate - [print] the resp       
��(K�hP���J��G�w�nQG=i�U�(g�=�p���0�3`_����To�3�A��Բ�m�

有人可以在这里给我建议吗?谢谢!

标签: karate

解决方案


这听起来像是对空手道的增强请求。

如果您对代码更改有一些想法,请像提交链接问题的人一样提交 PR。至少,请提交一种复制方式:https ://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

当然,在此之前您可以检查 1.0 RC 版本是否解决了这个问题 - 因为 HTTP 客户端被重构了一点:https ://github.com/intuit/karate/wiki/1.0-upgrade-guide

编辑 - OP 在我在下面添加的评论中提供了答案。由于空手道将每个响应的原始字节公开为一个名为的变量responseBytes,因此您可以使用自定义 Java 实用程序进行转换:

byte[] bytes=(byte[]) responseBytes; //responseBytes object from Karate.
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); //transform into ByteArrayInputstream
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream); //Convert gzipInputstream
final String decompressedOutput = IOUtils.toString(gzipInputStream,StandardCharsets.UTF_8); 

推荐阅读