【问题标题】: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;
}