简体   繁体   中英

Get http response code and all available body

I want ot implement WebFlux example client which can make request with http params and get the response body and http response code. I tried this:

public ClientResponse execute(NotificationMessage nm)
Mono<String> transactionMono = Mono.just(convertedString);
        return client.post().uri(builder -> builder.build())
                .header(HttpHeaders.USER_AGENT, "agent")
                .body(transactionMono, String.class).exchange().block();
    }

    private static String convert(Map<String, String> map) throws UnsupportedEncodingException {
        String result = map.entrySet().stream().map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
                .collect(Collectors.joining("&"));
        return result;
    }

    private static String encode(String s) {
        try {
            return URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }

Can you give me some advice after .exchange() how I can get the http status code and all available body.

From the ClientResponse object returned by exchange you can use response.statusCode() to get the status and use response.bodyToMono() or bodyToFlux() to get the actual body. You should avoid using .block() in reactive programming and use .subscribe() or .flatMap() or other operators to get the data from Mono or Flux objects. Read more about reactive programming and Project reactor (used by spring webflux) here.

For eg:

public Mono<Data> execute(NotificationMessage nm)
    return client.post().uri(builder -> builder.build())
                .header(HttpHeaders.USER_AGENT, "agent")
                .body(transactionMono, String.class).exchange()
                .flatMap(response -> {
                        HttpStatus code = response.statusCode();
                        Data data = response.bodyToMono(Data.class);
                        return data;
                });
}

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