首页 > 解决方案 > Wiremock gzip;deflate 标头被忽略?

问题描述

我正在使用 Wiremock 编写一个简单的单元测试,以测试我的 http 客户端是否可以按需禁用 gzip 压缩。我面临的问题是,wiremock 似乎忽略了 Accept-Encoding: gzip,deflate 标头。这是一个简单的测试用例:

   @Test
    public void getContentWithGZIP() throws Exception {
        WireMockServer wireMockServer = new WireMockServer(wireMockConfig().port(8060));
        wireMockServer.start();
        wireMockServer.stubFor(post(urlEqualTo("/gzip-response")).willReturn(aResponse().withBody("body text")));

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("http://localhost:8060/gzip-response");
        StringEntity entity = new StringEntity("{payload:null}");
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        logger.debug("response={}", EntityUtils.toString(httpEntity));
        Arrays.asList(response.getAllHeaders()).stream().forEach(header -> logger.debug(" header={} value={}", header.getName(), header.getValue()));
        Header contentEncodingHeader = response.getFirstHeader("Content-Encoding");
        Assert.assertEquals("gzip", contentEncodingHeader.getValue());
    }

我正在使用wiremock 2.5和apache http客户端4.4.1在调试级别使用apache客户端运行测试我可以看到“在线”数据。我可以看到请求包含 Accepting-Encodging" 标头

16:01:23.283 DEBUG org.apache.http.wire - http-outgoing-0 >> "POST /gzip-response HTTP/1.1[\r][\n]"
16:01:23.283 DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Length: 14[\r][\n]"
16:01:23.283 DEBUG org.apache.http.wire - http-outgoing-0 >> "Content-Type: text/plain; charset=ISO-8859-1[\r][\n]"
16:01:23.283 DEBUG org.apache.http.wire - http-outgoing-0 >> "Host: localhost:8060[\r][\n]"
16:01:23.283 DEBUG org.apache.http.wire - http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
16:01:23.283 DEBUG org.apache.http.wire - http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.4.1 (Java/1.8.0_212)[\r][\n]"
16:01:23.283 DEBUG org.apache.http.wire - http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
16:01:23.284 DEBUG org.apache.http.wire - http-outgoing-0 >> "[\r][\n]"

但是响应缺少Content-Encoding一个:

16:01:23.620 DEBUG org.apache.http.wire - http-outgoing-0 << "HTTP/1.1 200 OK[\r][\n]"
16:01:23.621 DEBUG org.apache.http.wire - http-outgoing-0 << "Transfer-Encoding: chunked[\r][\n]"
16:01:23.621 DEBUG org.apache.http.wire - http-outgoing-0 << "Server: Jetty(9.2.13.v20150730)[\r][\n]"
16:01:23.621 DEBUG org.apache.http.wire - http-outgoing-0 << "[\r][\n]"
16:01:23.621 DEBUG org.apache.http.wire - http-outgoing-0 << "9[\r][\n]"

也许我错过了明显的东西,但我找不到是什么。谁能告诉我问题出在哪里?

标签: javawiremock

解决方案


那是因为HttpClient默认情况下会为您解压缩,并且当它这样做时,它会从Response对象中删除这些标头。

请参阅此Github 链接,其中标头已在 ResponseContentEncoding.java 行中被删除

这个Jmeter 讨论线程提供了另一个团队如何处理相同场景的历史。


推荐阅读