When using WebClient's exchangeToMono()
the body retrieving part is always returning an empty Mono:
Example, the exposed service which returns a non-empty Mono
@PostMapping("/test")
public Mono<Pojo> getCalled(@RequestBody Pojo pojo) {
System.out.println(pojo); // always prints a non-null object
return Mono.just(pojo);
}
WebClient with .retrieve()
WebClient.create().post().uri(theUrl).bodyValue(p).retrieve().toEntity(Pojo.class).map(response -> {
if (response.getStatusCode().isError()) {
// do something;
}
return response.getBody();
}).single(); // always get a single element and does not fail
WebClient with .exchangeToMono()
WebClient.create().post().uri(theUrl).bodyValue(p).exchangeToMono(Mono::just).flatMap(response -> {
if (response.statusCode().isError()) {
// do something;
}
return response.bodyToMono(Pojo.class).single(); // fails with java.util.NoSuchElementException: Source was empty
});
Am I doing something wrong?