如何在 spring-boot web 客户端中发送请求正文?

How to send request body in spring-boot web client?

我在 spring 引导 Web 客户端中发送请求正文时遇到了一些问题。尝试像下面这样发送正文:

val body = "{\n" +
            "\"email\":\"test@mail.com\",\n" +
            "\"id\":1\n" +
            "}"
val response = webClient.post()
    .uri( "test_uri" )
    .accept(MediaType.APPLICATION_JSON)
    .body(BodyInserters.fromObject(body))
    .exchange()
    .block()

它不工作。 请求正文应采用 JSON 格式。 请告诉我哪里做错了。

您没有设置 "Content-Type" 请求 header,因此您需要将 .contentType(MediaType.APPLICATION_JSON) 附加到请求构建部分。

上面的回答是正确的:在你的Content-Typeheader中添加application/json解决了这个问题。不过,在这个答案中,我想提一下 BodyInserters.fromObject(body) 已被弃用。从 Spring Framework 5.2 开始,推荐使用 BodyInserters.fromValue(body).

您可以尝试如下:

public String wcPost(){

    Map<String, String> bodyMap = new HashMap();
    bodyMap.put("key1","value1");
 

    WebClient client = WebClient.builder()
            .baseUrl("domainURL")
            .build();


    String responseSpec = client.post()
            .uri("URI")
            .headers(h -> h.setBearerAuth("token if any"))
            .body(BodyInserters.fromValue(bodyMap))
            .exchange()
            .flatMap(clientResponse -> {
                if (clientResponse.statusCode().is5xxServerError()) {
                    clientResponse.body((clientHttpResponse, context) -> {
                        return clientHttpResponse.getBody();
                    });
                    return clientResponse.bodyToMono(String.class);
                }
                else
                    return clientResponse.bodyToMono(String.class);
            })
            .block();

    return responseSpec;
}