![](/img/trans.png)
[英]Spring Webclient : How to get the body on error when the http status code is 200
[英]Get status code of Spring WebClient request
我的目標是從 Spring WebClient 請求中獲取 HttpStatus。 請求的所有其他信息都無關緊要。
我這樣做的舊方法是:
WebClient.builder().baseUrl("url").build()
.get().exchange().map(ClientResponse::statusCode).block();
在 Spring Boot 2.4.x/Spring 5.3 中,WebClient 的exchange
方法被棄用,取而代之的是retrieve
。
在https://stackoverflow.com/a/65791800的幫助下,我設法創建了以下解決方案。
WebClient.builder().baseUrl("url").build()
.get().retrieve()
.toEntity(String.class)
.flatMap(entity -> Mono.just(entity.getStatusCode()))
.block();
但是,這看起來是一種非常“hacky”的方式,並且在收到 4xx 或 5xx 響應時不起作用(在這種情況下,結果為空)。
這個問題可以通過exchangeToMono
方法解決。 這導致以下代碼段。
WebClient.builder().baseUrl("url").build()
.get().exchangeToMono(response -> Mono.just(response.statusCode()))
.block();
可以通過以下方式改進retrieve
方法的使用,但仍然不是很干凈。
WebClient.builder().baseUrl("url").build()
.get().retrieve()
.onStatus(httpStatus -> true, clientResponse -> {
//Set variable to return here
status.set(clientResponse.statusCode());
return null;
})
.toBodilessEntity().block();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.