javaspring-bootgzipspring-webclient

How to make WebClient in Spring Boot work with gzip?


I use WebClient to get some data from a remote server. The remote server is capable of dealing with gzip. In other words if I send a GET request with "Accept-Encoding: gzip" it returns compressed content. And if the content is very small it doesn't compress the response.

My problem is with WebClient, which cannot handle gzip by default.

My code is as follows:

@Bean
WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager,
                    @Value("${test.url}") String authUserUri) {
    ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 =
            new ServletOAuth2AuthorizedClientExchangeFilterFunction(
                    authorizedClientManager);
    oauth2.setDefaultClientRegistrationId(AUTH_SERVER_OAUTH2_CLIENT_ID);
    final int size_mb = 10;
    final int size = size_mb * 1024 * 1024;
    final ExchangeStrategies strategies = ExchangeStrategies.builder()
            .codecs(codecs -> codecs.defaultCodecs().maxInMemorySize(size)).build();
    var webClientBuilder = WebClient.builder().apply(oauth2.oauth2Configuration())
            .baseUrl(authUserUri);

    //Detailed http communication logging for local profile.
    if (true) {
        webClientBuilder.codecs(configurer -> configurer.defaultCodecs().enableLoggingRequestDetails(true))
                .clientConnector(new ReactorClientHttpConnector(
                        HttpClient.create().wiretap(this.getClass().getCanonicalName(), LogLevel.INFO, AdvancedByteBufFormat.TEXTUAL)));
    }
    return webClientBuilder.exchangeStrategies(strategies).build();
}

I modified the webClientBuilder so that the WebClient sends "Accept-Encoding: gzip":

var webClientBuilder = WebClient.builder().apply(oauth2.oauth2Configuration())
        .baseUrl(authUserUri).defaultHeaders(httpHeaders -> {
            httpHeaders.add("Accept-Encoding", "gzip");
        });

In the logs I see that it sends that header. The response body from the remote server looks mumble jumble so I guess it is gzipped but my WebClient is not able to read it. So, my question is; How I can make WebClient capable of decoding gzip?


Solution

  • You can replace client creation here:

    HttpClient.create().wiretap(this.getClass().getCanonicalName(), LogLevel.INFO, AdvancedByteBufFormat.TEXTUAL)));

    to:

    HttpClient.create().compress(true);