简体   繁体   中英

Access response status code for successful requests using Spring WebClient

I need to be able to access the status code of a request. The call can be successful in either of two ways 200 or 201. This is obvious when calling via postman but using the web client, so far I haven't been able to determine which has occurred.

webClient.post()
        .uri(url)
        .header(HttpHeaders.ACCEPT, MediaType.ALL_VALUE)
        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .header(HttpHeaders.AUTHORIZATION, bearerToken)
        .bodyValue(bodyMap)
        .retrieve()
        .onStatus(
                HttpStatus.BAD_REQUEST::equals,
                response -> response.bodyToMono(String.class).map(Exception::new))
        .bodyToMono(Map.class)

I was thinking maybe I could set an integer variable using within the onStatus() lambda function. Is it even possible to access external variables within a lambda function?

int responseStatus;

// post call
.onStatus(
            HttpStatus.CREATED::equals,
            response -> ... // do something to set responseStatus

You could use .toEntity(Class<T> bodyClass) method to get entity wrapped in response object ResponseEntity<T>

var response = webClient.post()
        .uri(uri)
        .retrieve()
        .toEntity(Map.class)
        .map(res -> {
            if (res.getStatusCode().equals(HttpStatus.OK)) {
                ...
            }

            return res.getBody();
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM