Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract response header & status code from Spring 5 WebClient ClientResponse

Tags:

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

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.

like image 550
Renus11 Avatar asked May 07 '18 23:05

Renus11


People also ask

How do I get the HTTP response header?

In order to extract a header from a response, you will have to use Http. request along with the expectStringResponse function, which includes the full response including headers. Here is an example on ellie-app.com which returns the value of content-type as an example.

How do I get the response header cookie?

Just set the Set-Cookie header in the response from the server side code. The browser should save it automatically. As a developer, you may be able to inspect the value of the cookies using "Developer Tools". And the same cookie will be sent in subsequent requests to the same domain, until the cookie expires.


1 Answers

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

then you can convert bodyToMono etc

like image 147
Kevin Hussey Avatar answered Oct 23 '22 13:10

Kevin Hussey