如何提取响应头 &来自 Spring 5 WebClient ClientResponse 的状态码 [英] How to extract response header & status code from Spring 5 WebClient ClientResponse

查看:30
本文介绍了如何提取响应头 &来自 Spring 5 WebClient ClientResponse 的状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Spring Reactive 框架的新手 &尝试将 Springboot 1.5.x 代码转换为 Springboot 2.0.我需要在一些过滤后返回响应头,正文 &来自 Spring 5 WebClient ClientResponse 的状态代码.我不想使用 block() 方法,因为它会将其转换为同步调用.我可以使用 bodyToMono 很容易地获得 responsebody.另外,我正在获取状态代码、标题和body 如果我只是返回 ClientResponse 但我需要根据 statusCode & 处理响应头参数.我尝试了订阅、flatMap 等,但没有任何效果.

I am new to Spring Reactive framework & trying to convert Springboot 1.5.x code into Springboot 2.0. I need to return response header after some filtering, body & status code from Spring 5 WebClient ClientResponse. I do not want to use block() method as it will convert it into sync call. I am able to get responsebody pretty easily using bodyToMono. Also, I am getting status code, headers & body if I am just returning ClientResponse but I need to process response based on statusCode & header parameters. I tried subscribe, flatMap etc. but nothing works.

例如- 下面的代码将返回响应正文

E.g. - Below code will return response Body

Mono<String> responseBody =  response.flatMap(resp -> resp.bodyToMono(String.class));

但类似的范式无法获得 statusCode &响应头.有人可以帮我提取 statusCode &使用 Spring 5 响应式框架的标头参数.

But similar paradigm is not working to get statusCode & Response headers. Can someone help me in extracting statusCode & header parameters using Spring 5 reactive framework.

推荐答案

可以使用 webclient e.g. 的交换功能

You can use the exchange function of webclient e.g.

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 等

then you can convert bodyToMono etc

这篇关于如何提取响应头 &amp;来自 Spring 5 WebClient ClientResponse 的状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆