gzipretrofit2okhttp

Retrofit: how to parse GZIP'd response without Content-Encoding: gzip header


I'm trying to process a server response which is GZIP'd. The response comes with a header

Content-Type: application/x-gzip

but does not have header

Content-Encoding: gzip

If I add that header using a proxy, the response gets parsed just fine. I don't have any control over the server, so I can't add the header.

Can I force Retrofit to treat it as GZIP content? Is there a better way? The URL for the server is: http://crowdtorch.cms.s3.amazonaws.com/4474/Updates/update-1.xml


Solution

  • There is a better way than reinventing the wheel. Just add the Content-Encoding header yourself.

    .addNetworkInterceptor((Interceptor.Chain chain) -> {
        Request req = chain.request();
        Headers.Builder headersBuilder = req.headers().newBuilder();
    
        String credential = Credentials.basic(...);
        headersBuilder.set("Authorization", credential);
    
        Response res = chain.proceed(req.newBuilder().headers(headersBuilder.build()).build());
    
        return res.newBuilder()
            .header("Content-Encoding", "gzip")
            .header("Content-Type", ""application/json")
            .build();
    })
    

    In fact, your code is a classic example of the evils of using internal code (like com.sun packages from the JDK). RealResponseBody doesn't have that constructor anymore.