使用MockWebServer返回gzip响应

时间:2019-04-23 13:52:23

标签: java android okhttp mockwebserver

我在为使用OkHttp的客户端编写涉及gzip压缩响应的测试时遇到问题。本质上,我正在做的是:

@Test
public void okHttp_whenResponseIsGzipped_returnsBody() throws Exception {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.start();

    mockWebServer.enqueue(new MockResponse()
            .addHeader("Content-Encoding", "gzip")
            .setBody(new String(compress("I AM BODY"))));

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(mockWebServer.url("")).build();
    Response response = okHttpClient.newCall(request).execute();

    assertThat(response.body().string(), equalTo("I AM BODY"));
}

public static byte[] compress(String data) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
    GZIPOutputStream gzip = new GZIPOutputStream(bos);
    gzip.write(data.getBytes());
    gzip.close();
    byte[] compressed = bos.toByteArray();
    bos.close();
    return compressed;
}

但是,当我运行此测试时,它在调用response.body().string()时会爆炸:

java.io.IOException: ID1ID2: actual 0x00001fef != expected 0x00001f8b

at okio.GzipSource.checkEqual(GzipSource.java:205)
at okio.GzipSource.consumeHeader(GzipSource.java:120)
at okio.GzipSource.read(GzipSource.java:73)
at okio.RealBufferedSource.request(RealBufferedSource.java:68)
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:417)
at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:401)
at okhttp3.internal.Util.bomAwareCharset(Util.java:471)
at okhttp3.ResponseBody.string(ResponseBody.java:175)

我压缩响应正文的方式有问题吗?我需要做更多的工作来设置MockWebServer吗?

1 个答案:

答案 0 :(得分:0)

请勿执行new String(body),因为那样会将其转换为字符串。而是执行new Buffer().write(body),它不会转换。