我正在尝试通过 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/