Search code examples
javaspringspring-bootspring-webclient

Get status code of Spring WebClient request


My goal is to get the HttpStatus from a Spring WebClient request. All other information of the request is irrelevant.

My old way of doing this was:

WebClient.builder().baseUrl("url").build()
        .get().exchange().map(ClientResponse::statusCode).block();

With Spring Boot 2.4.x/Spring 5.3, the exchange method of WebClient is deprecated in favor of retrieve.

With the help of https://stackoverflow.com/a/65791800 i managed to create the following solution.

WebClient.builder().baseUrl("url").build()
        .get().retrieve()
        .toEntity(String.class)
        .flatMap(entity -> Mono.just(entity.getStatusCode()))
        .block();

However, this looks like a very "hacky" way and and does not work when 4xx or 5xx responses are received (In this case the result is null).


Solution

  • This problem can be solved with the method exchangeToMono. This results into the following snippet.

    WebClient.builder().baseUrl("url").build()
            .get().exchangeToMono(response -> Mono.just(response.statusCode()))
            .block();
    

    The usage of the retrieve method can be improved in the following way, still not very clean.

    WebClient.builder().baseUrl("url").build()
            .get().retrieve()
            .onStatus(httpStatus -> true, clientResponse -> {
                //Set variable to return here
                status.set(clientResponse.statusCode());
                return null;
            })
            .toBodilessEntity().block();