1

I have been looking for how to enable transparent processing of gzip'ed response using RestTemplate with OkHttp3 set as its http client.

Below is how I define the bean for RestTemplate:

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {

        RestTemplate restTemplate = restTemplateBuilder //
                .rootUri(_endpoint) //
                .additionalInterceptors(new ClientHttpRequestInterceptor() {

                    @Override
                    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                            ClientHttpRequestExecution execution) throws IOException {

                        request.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, "gzip");

                        ClientHttpResponse response = execution.execute(request, body);

                        return response; // if I set a breakpoint here, I
                                         // can see it's OkHttp3ClientHttpResponse
                    }
                }) //
                .build();

        return restTemplate;
    }

In my pom.xml I have:

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>

Sure there is a solution to enable gzip response processing. But to me that's no transparent.

There is a solution for RestTemplate + Apache HttpClient which I only need to switch the pom.xml dependency to

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

It works with the same Bean code above. That's what I call transparent. However due to a number of reasons I had to use OkHttp3.

I've looked at the official doc of OkHttp3 but it doesn't give a specific instruction. This is ironic, because if it's truly transparent I shouldn't need to do anything.

If anyone knows any details, please help. Appreicated!

wxh
  • 619
  • 7
  • 20

1 Answers1

0

It's transparent if you don't set Accept-Encoding or Range.

https://github.com/square/okhttp/blob/f8fd4d08decf697013008b05ad7d2be10a648358/okhttp/src/main/kotlin/okhttp3/internal/http/BridgeInterceptor.kt#L66-L73

Add a logging interceptor as a networkInterceptor so you can see what headers are being sent and received. This should show the gzipped response before unzipping

https://github.com/square/okhttp/blob/f8fd4d08decf697013008b05ad7d2be10a648358/okhttp/src/main/kotlin/okhttp3/internal/http/BridgeInterceptor.kt#L90-L104

Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69
  • Thanks. I should've read the code, but I believe I won't be the only one having this question. – wxh Nov 13 '21 at 04:36
  • Yep, it does show up in similar stackoverflow questios, and various OkHttp tutorials so you are not the only one. "Transparent GZIP shrinks download sizes" is meant to sound automatic. – Yuri Schimke Nov 13 '21 at 08:14