Search code examples
javaspringspring-bootwebclientspring-webclient

Spring webclient how to extract response body multiple times


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?


Solution

  • 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);