1
votes

I have started using WebClient(org.springframework.web.reactive.function.client.WebClient) for calling rest services. I have 2 classes say Utility.java and ServiceImpl.java. ServiceImpl.java is where I use WebClient. A post call I am making looks like -

ClientResponse response = webClient.post()
            .uri(path)
            .body(Mono.just(inputDTO),InputDTO.class)
            .exchange()
            .block();

(ClientResponse above is org.springframework.web.reactive.function.client.ClientResponse) (I am using exchange instaed of retrive because I want headers as well as status code)

Now trying to convert this response into some DTO - ResponseDTO.

Mono<ResponseEntity<ResponseDTO>> mono = response.toEntity(ResponseDTO.class);
        ResponseEntity<ResponseDTO> resEntity = mono.block();
        ResponseDTO myObj = resEntity.getBody();

So myObj is an object of ResponseDTO class.

The issue is - when I perform the conversion of 'response into ResponseDTO.java' in my utility class, I get myObj = null. But if I do it in my ServiceImpl.java (just after calling post API), it returns the proper body (ResponseDTO object). The same issue occurs even if I perform the conversion and post call operation in two different methods in the ServiceImpl.java. Do I need to configure something here?

1

1 Answers

0
votes

I figured out what was the issue. After calling REST api, body in the response if flushed out after I read it from the response for the first time. I had a Sysout statement in service implementation class where I was reading the body content.

Recommendation: Read the body content only once and store it in a variable. Use it wherever required.