Returning gzip responses with MockWebServer

seadowg :

I'm having a problem writing a test involving gzipped responses for a client that uses OkHttp. In essence what I'm doing is:

@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;
}

However, when I run this test it explodes at the call to response.body().string() with:

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)

Is there something wrong with how I'm compressing my response body? Do I need to do more work to setup MockWebServer?

Jesse Wilson :

Do not do new String(body) because that converts it to a string. Instead do new Buffer().write(body) which doesn't convert.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166615&siteId=1