【问题标题】:How to send request body in spring-boot web client?如何在 spring-boot Web 客户端中发送请求正文?
【发布时间】:2019-04-13 00:04:36
【问题描述】:

我在 Spring Boot 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 格式。 请让我知道我在哪里做错了。

【问题讨论】:

    标签: spring-boot kotlin webclient spring-webflux


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      以上答案是正确的:在 Content-Type 标头中添加 application/json 可以解决问题。不过,在这个答案中,我想提一下 BodyInserters.fromObject(body) 已被弃用。从 Spring Framework 5.2 开始,建议使用BodyInserters.fromValue(body)

      【讨论】:

        【解决方案3】:

        你可以尝试如下:

        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;
        }
        

        【讨论】:

        • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 2019-01-15
        • 2021-12-16
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        • 2015-11-09
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        相关资源
        最近更新 更多