How to extract response header & status code from Spring 5 WebClient ClientResponse
You can use the exchange function of webclient e.g.
Mono<String> reponse = webclient.get().uri("https://stackoverflow.com").exchange().doOnSuccess(clientResponse -> System.out.println("clientResponse.headers() = " + clientResponse.headers())).doOnSuccess(clientResponse -> System.out.println("clientResponse.statusCode() = " + clientResponse.statusCode())).flatMap(clientResponse -> clientResponse.bodyToMono(String.class));
then you can convert bodyToMono etc
I needed to check the response details(headers, status, etc) and body as well.
The only way I was able to do it was by using .exchange()
with two subscribe()
as the following example:
Mono<ClientResponse> clientResponse = WebClient.builder().build() .get().uri("https://stackoverflow.com") .exchange(); clientResponse.subscribe((response) -> { // here you can access headers and status code Headers headers = response.headers(); HttpStatus stausCode = response.statusCode(); Mono<String> bodyToMono = response.bodyToMono(String.class); // the second subscribe to access the body bodyToMono.subscribe((body) -> { // here you can access the body System.out.println("body:" + body); // and you can also access headers and status code if you need System.out.println("headers:" + headers.asHttpHeaders()); System.out.println("stausCode:" + stausCode); }, (ex) -> { // handle error }); }, (ex) -> { // handle network error });
I hope it helps.If someone knows a better way to do it, please let us know.
For status code you can try this:
Mono<HttpStatus> status = webClient.get() .uri("/example") .exchange() .map(response -> response.statusCode());
For headers:
Mono<HttpHeaders> result = webClient.get() .uri("/example") .exchange() .map(response -> response.headers().asHttpHeaders());