英文:
Spring webclient how to extract response body multiple times
问题
如何重复使用WebClient客户端响应?我正在使用WebClient进行同步请求和响应。我对WebClient还不太了解,不确定如何在多个地方提取响应正文。
WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
下面是我调用API返回有效响应的代码:
ClientResponse clientResponse;
clientResponse = webClient.get()
.uri("/api/v1/data")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.block();
如何在多个地方使用clientResponse
?我只能提取响应正文一次:
String response = clientResponse.bodyToMono(String.class).block(); // 响应有值
当我尝试第二次提取响应正文(在不同的类中),它为空:
String response = clientResponse.bodyToMono(String.class).block(); // 响应为空
所以,有人可以解释为什么第二次响应为空,以及如何多次提取响应正文吗?
英文:
how to re-use webclient client response? I am using webclient for synchronous request and response. I am new to webclient and not sure how to extract response body in multiple places
WebClient webClient = WebClient.builder().baseUrl("http://localhost:8080").build();
below is my call to API which returns valid response
ClientResponse clientResponse;
clientResponse = webClient.get()
.uri("/api/v1/data")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.block();
How to use clientResponse in multiple places? 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
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?
答案1
得分: 0
WebClient基于Reactor-netty,并且接收的缓冲区是一次性的。
你可以在第一次缓存结果,然后重复使用它。
你可以参考Spring Cloud Gateway中的这个问题:https://github.com/spring-cloud/spring-cloud-gateway/issues/1861
或者参考Spring Cloud Gateway为缓存请求体所做的操作:https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/AdaptCachedBodyGlobalFilter.java
或者你可以像这样编写你的代码:
String block = clientResponse.bodyToMono(String.class).block();
然后下次你可以使用这个body:
```java
Mono.just(block);
英文:
WebClient is based on Reactor-netty and the buffer received is one time thing.
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
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
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论