How to compress the body of Spring WebClient post request?
Asked Answered
L

1

2

I am doing some testing with Spring WebClient. In the following codes, I have set the compress to true. However when I check the debug logs, I can see the "accept-encoding: gzip" header is added, but the body is not compressed. Any way to force compress on post request body? Thanks.

HttpClient httpClient = HttpClient.create().compress(true).wiretap(true);

WebClient webClient = WebClient.builder()
                .baseUrl("https://jsonplaceholder.typicode.com")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();

Post post = new Post();

        post.setUserId(1000L);
        post.setId(2000L);
        post.setTitle("Reactor Netty");

        StringBuffer sb = new StringBuffer();
        IntStream.range(1, 1000).forEach(i -> sb.append("Spring boot webclient"));
        post.setBody(sb.toString());

        Post p = webClient.post().uri("/posts").syncBody(post).retrieve().bodyToMono(Post.class).block();
Lipophilic answered 20/8, 2019 at 6:45 Comment(2)
Do you want to send the post request body compressed or you want to receive the response compressed?Sanctum
Both way. The compress() method gives me the impression that this task is taken care of by the library.Lipophilic
K
4

Please refer to this.

.compress(true) is for the server to response as gzip. That's why your post body is not compressed.

I am not familiar with manual http-client and web-client. When I use Spring, I use RestTemplate. This answer details how to force zipping your request body.

Kaffir answered 20/8, 2019 at 6:53 Comment(3)
Thanks for the answer. One can definitely gzip the body with extra codes. But I was thinking this common task may be available out of box.Lipophilic
compress(true) is for the server responses. For the request body, Netty does not support it by default: github.com/netty/netty/issues/2132Sanctum
@VioletaGeorgieva Thanks Violeta! You answered my question.Lipophilic

© 2022 - 2024 — McMap. All rights reserved.