我是Spring Reactive框架的新手&正在尝试将Springboot1.5.x代码转换为Springboot2.0。我需要从Spring5 WebClient ClientResponse返回一些过滤后的响应头、正文和状态代码。我不想使用block()方法,因为它会将它转换为sync调用。使用bodyToMono,我可以很容易地获得响应体。此外,如果我只是返回ClientResponse,但我需要根据statusCode和header参数处理响应,我会得到状态代码、headers和body。我尝试了订阅,flatMap等,但都不起作用。
例如-下面的代码将返回响应正文
Mono<String> responseBody = response.flatMap(resp -> resp.bodyToMono(String.class));但类似的范例无法获得statusCode & Response报头。有没有人能帮我用Spring5 reactive框架提取statusCode & header参数?
发布于 2018-05-18 12:11:15
你可以使用webclient的交换功能,例如
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));然后,您可以转换bodyToMono等
发布于 2018-12-10 00:12:03
我还需要检查响应细节(报头、状态等)和正文。
我能够做到这一点的唯一方法是使用带有两个subscribe()的.exchange(),如下所示:
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
});我希望它能帮上忙。如果有人知道更好的方法,请让我们知道。
发布于 2019-10-31 14:00:12
对于状态代码,您可以尝试执行以下操作:
Mono<HttpStatus> status = webClient.get()
.uri("/example")
.exchange()
.map(response -> response.statusCode());对于标头:
Mono<HttpHeaders> result = webClient.get()
.uri("/example")
.exchange()
.map(response -> response.headers().asHttpHeaders());https://stackoverflow.com/questions/50223891
复制相似问题