[英]Spring webclient how to extract response body multiple times
how to re-use webclient client response?如何重用webclient客户端响应? I am using webclient for synchronous request and response.我正在使用 webclient 进行同步请求和响应。 I am new to webclient and not sure how to extract response body in multiple places我是 webclient 的新手,不知道如何在多个地方提取响应正文
WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
below is my call to API which returns valid response下面是我对 API 的调用,它返回有效响应
ClientResponse clientResponse;
clientResponse = webClient.get()
.uri("/api/v1/data")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.block();
How to use clientResponse in multiple places?如何在多个地方使用 clientResponse? only one time I am able to extract response body只有一次我能够提取响应体
String response = clientResponse.bodyToMono(String.class).block(); // response has value
When I try to extract the response body second time (in a different class), it's null当我第二次尝试提取响应主体(在不同的类中)时,它是 null
String response = clientResponse.bodyToMono(String.class).block(); // response is null
So, can someone explain why response is null second time and how to extract the response body multiple times?那么,有人可以解释为什么响应是 null 第二次以及如何多次提取响应正文?
WebClient is based on Reactor-netty and the buffer received is one time thing. WebClient 基于 Reactor-netty,接收到的缓冲区是一次性的。
One thing you could do is to cache the result at the first time and then reuse it.您可以做的一件事是在第一次缓存结果然后重用它。
You can refer to this issue in spring cloud gateway: https://github.com/spring-cloud/spring-cloud-gateway/issues/1861这个问题可以参考spring云网关: https://github.com/spring-cloud/spring-cloud-gateway/issues/1861
Or refer to what Spring Cloud gateway do for caching request body: https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/AdaptCachedBodyGlobalFilter.java或者参考Spring云网关对缓存请求体做了什么: https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/main/java/org /springframework/cloud/gateway/filter/AdaptCachedBodyGlobalFilter.java
Or you can write your code like:或者您可以编写如下代码:
String block = clientResponse.bodyToMono(String.class).block();
And next time you can use this body:下次你可以使用这个身体:
Mono.just(block);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.