简体   繁体   English

获取 http 响应代码和所有可用的正文

[英]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.我想实现 WebFlux 示例客户端,它可以使用 http 参数发出请求并获取响应正文和 http 响应代码。 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.你能在.exchange()之后给我一些建议如何获取 http 状态代码和所有可用的正文。

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.从交换返回的 ClientResponse 对象中,您可以使用 response.statusCode() 获取状态并使用 response.bodyToMono() 或 bodyToFlux() 获取实际正文。 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.你应该避免在反应式编程中使用 .block() 并使用 .subscribe() 或 .flatMap() 或其他运算符从 Mono 或 Flux 对象获取数据。 Read more about reactive programming and Project reactor (used by spring webflux) here.在此处阅读有关反应式编程和 Project reactor(由 spring webflux 使用)的更多信息。

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;
                });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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