【问题标题】:How to compress the body of Spring WebClient post request?如何压缩 Spring WebClient 发布请求的正文?
【发布时间】:2019-12-25 08:08:20
【问题描述】:

我正在使用 Spring WebClient 进行一些测试。在以下代码中,我已将 compress 设置为 true。但是,当我检查调试日志时,我可以看到添加了“accept-encoding: gzip”标头,但正文未压缩。有什么方法可以强制压缩发布请求正文?谢谢。

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();

【问题讨论】:

  • 您想发送压缩后的请求正文还是接收压缩后的响应?
  • 双向。 compress() 方法给我的印象是这个任务由库处理。

标签: spring-boot reactor-netty spring-webclient


【解决方案1】:

请参考this

.compress(true) 用于服务器以 gzip 的形式响应。这就是为什么您的帖子正文没有被压缩的原因。

我不熟悉手动 http-client 和 web-client。当我使用 Spring 时,我使用 RestTemplate。 This answer 详细说明了如何强制压缩您的请求正文。

【讨论】:

  • 感谢您的回答。绝对可以用额外的代码压缩身体。但我在想这个常见的任务可能是开箱即用的。
  • compress(true) 用于服务器响应。对于请求体,Netty 默认不支持:github.com/netty/netty/issues/2132
  • @VioletaGeorgieva 谢谢维奥莱塔!你回答了我的问题。
猜你喜欢
  • 2020-06-22
  • 1970-01-01
  • 2019-06-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2019-05-07
  • 2012-08-22
相关资源
最近更新 更多