java - Webclient 发送没有正文的 POST 将得到 IllegalStateException

标签 java spring-boot spring-webflux

我正在尝试通过 WebClient 对 api 进行 POST 调用,无需请求正文(该 api 不需要正文):

webClient.post()
         .uri("url")
         .retrieve()
         .bodyToMono(CustomResponse.class);

但是调用返回异常:

The underlying HTTP client completed without emitting a response.java.lang.IllegalStateException: The underlying HTTP client completed without emitting a response.

对于另一个需要请求正文的 API,我可以成功地进行 POST 调用,没有任何问题:

webClient.post()
         .uri("url")
         .bodyValue("value")
         .retrieve()
         .bodyToMono(CustomResponse.class);

问题是否与 WebClient 的请求正文有关?我该如何修复它?

更新

发生错误的原因是我通过 .defaultHeader("ContentType", JSON) 添加了 Webclient 的 ContentType header 。 删除标题后问题就消失了。

最佳答案

看起来下游 Web 服务响应太慢并且超出了连接超时,因此您遇到了此问题。

如果您不需要(或响应没有正文),您可以使用 .toBodilessEntity() 代替。所以你的代码片段可以重写:

webClient.post()
         .uri("url")
         .retrieve()
         .toBodilessEntity();

为什么要使用它?因为你始终负责资源的释放。请阅读NOTE section .

When using exchange(), it is the responsibility of the application to consume any response content regardless of the scenario (success, error, unexpected data, etc). Not doing so can cause a memory leak. See ClientResponse for a list of all the available options for consuming the body.

关于java - Webclient 发送没有正文的 POST 将得到 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60349444/

相关文章:

Java react 堆 : How to produce Flux from stdin?

java - 将 RuntimeException 作为异常重新抛出

java - 使用spring security成功登录后如何将对象添加到 View 中?

java - Spring Batch ItemReader + RabbitMQ - 未指定 'queue'

java - SpringBoot Webflux 无法返回 application/xml

spring-webflux - Spring Web Flux 和 Reactor 中的 Map 与 FlatMap

java - MyEclipse Blue 10.7 错误地在 war 中包含引用的 Java 库 jar

java - 我应该如何将 try-with-resources 与 JDBC 结合使用?

java - 使用HashMap <String,Drawable>时需要使用什么声明?

java - Spring Boot Autowiring 空值