Skip to content

WebClient's ResponseSpec should provide access to response headers #22368

Closed
@csabakos

Description

@csabakos

Affects: 5.1.4


This in an enhancement request for WebClient.

Currently there are two ways to process the response with WebClient:

  1. WebClient#exchange() gives full access to the ClientResponse (including the HTTP response headers), but it requires one to handle erroneous HTTP status codes manually.
  2. WebClient#retrieve() simplifies error handling, but prevents access to ClientResponse.

I find myself using retrieve() almost exclusively, but sometimes I have to resort to exchange() (and doing my own error handling) due to the limitation described above.

It would be really nice for WebClient#retrieve() to provide access to ClientResponse (or at least the HTTP response headers) while still taking care of the bad status code handling.

An example use case of this is extracting a value from a HTTP header or a cookie in addition to deserializing the body to an object.

A potential implementation of this could be to add Mono<ClientResponse> clientResponse(); to WebClient.ResponseSpec. DefaultResponseSpec would call .cache() on the responseMono in the constructor, and return that from the new clientResponse() method.

That would allow one to write something like:

WebClient.ResponseSpec responseSpec = webClient.get().uri("http://...").retrieve();
responseSpec.bodyToMono(MyObject.class)
    .zipWith(responseSpec.clientResponse())
    .map((body, clientResponse) -> {
        // Access clientResponse.headers(), etc.
    }
    ...

An alternative solution could be to simply make DefaultResponseSpec public, so that one could do this manually:

Mono<ClientResponse> clientResponseMono = webClient.get().uri("http://...").exchange().cache();
new DefaultResponseSpec(clientResponseMono)
    .bodyToMono(MyObject.class)
    .zipWith(clientResponseMono)
    .map((body, clientResponse) -> {
        // Access clientResponse.headers(), etc.
    }
    ...

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions