0

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?

Pratap A.K
  • 4,337
  • 11
  • 42
  • 79
  • Why? You shouldn't need this. Compilers only read the source file once, and they're a lot more complex than anything you're likely to be doing. – user207421 Aug 06 '20 at 04:21
  • Does this answer your question? [Spring-boot Resttemplate response.body is null while interceptor clearly shows body](https://stackoverflow.com/questions/49062866/spring-boot-resttemplate-response-body-is-null-while-interceptor-clearly-shows-b) – Abhijit Sarkar Aug 07 '20 at 03:37
  • @AbhijitSarkar I am using WebClient, not RestTemplate – Pratap A.K Aug 07 '20 at 03:48

1 Answers1

0

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);
Hash Jang
  • 599
  • 3
  • 11