缺少 Content-Length 标头使用 WebClient 发送 POST 请求(SpringBoot 2.0.2.RELEASE) [英] Missing Content-Length header sending POST request with WebClient (SpringBoot 2.0.2.RELEASE)

查看:56
本文介绍了缺少 Content-Length 标头使用 WebClient 发送 POST 请求(SpringBoot 2.0.2.RELEASE)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WebClient (SpringBoot 2.0.2.RELEASE) 发送带有 SOAP 请求的 POST,但缺少Content-Length"所需的标头遗留 API.

I'm using WebClient (SpringBoot 2.0.2.RELEASE) to send a POST with SOAP request, but it is missing "Content-Length" header required by the legacy API.

是否可以将 WebClient 配置为包含Content-Length"标头?Spring 框架问题已为 EncoderHttpMessageWriter 解决并引入在 SpringBoot 2.0.1 中,但它似乎不适用于 JAXB.

Is it possible to configure WebClient to include "Content-Length" header? There is an Spring Framework Issue resolved and introduced for EncoderHttpMessageWriter in SpringBoot 2.0.1, but it seems not to work for JAXB.

我尝试使用 BodyInserters:

webClient.post().body(BodyInserters.fromObject(request)).exchange();

syncBody:

webClient.post().syncBody(request).exchange();

它们都不适用于 WebClient.但是,当使用 RestTemplate 时,会设置 Content-Length 并且 API 响应成功

None of them worked for WebClient. Though, when RestTemplate is used, Content-Length is set and API responds with success

推荐答案

WebClient 是一个流客户端,在流完成之前设置内容长度有点困难.到那时,标题早已不复存在.如果您使用旧版,您可以重用您的单声道(单声道/通量可以重用,Java 流不能)并检查长度.

WebClient is a streaming client and it's kind of difficult to set the content length until the stream has finished. By then the headers are long gone. If you work with legacy, you can re-use your mono (Mono/Flux can be reused, Java streams not) and check the length.

    public void post() {

    Mono<String> mono = Mono.just("HELLO WORLDZ");

    final String response = WebClient.create("http://httpbin.org")
            .post()
            .uri("/post")
            .header(HttpHeaders.CONTENT_LENGTH,
                    mono.map(s -> String.valueOf(s.getBytes(StandardCharsets.UTF_8).length)).block())
            .body(BodyInserters.fromPublisher(mono, String.class))
            .retrieve()
            .bodyToMono(String.class)
            .block();

    System.out.println(response);

}

我的一位同事(干得好 Max!)想出了更简洁的解决方案,我添加了一些包装代码以便进行测试:

A colleague (well done Max!) of mine came up with cleaner solution, I added some wrapping code so it can be tested:

    Mono<String> my = Mono.just("HELLO WORLDZZ")
            .flatMap(body -> WebClient.create("http://httpbin.org")
                    .post()
                    .uri("/post")
                    .header(HttpHeaders.CONTENT_LENGTH,
                            String.valueOf(body.getBytes(StandardCharsets.UTF_8).length))
                    .syncBody(body)
                    .retrieve()
                    .bodyToMono(String.class));

    System.out.println(my.block());

这篇关于缺少 Content-Length 标头使用 WebClient 发送 POST 请求(SpringBoot 2.0.2.RELEASE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆