Home > Mobile >  Get headers from response with Spring Boot 2 WebClient
Get headers from response with Spring Boot 2 WebClient

Time:09-23

I would like to receive the headers (especially the content-type) from the webclient response. I found this code with flatmap-mono-getHeaders, but it doesn't work.

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'image/tiff' not supported for bodyType=org.company.MyResponse

How can I fix it? Or maybe can someone recommend a simpler solution.

Mono<Object> mono = webClient.get()
                                .uri(path)
                                .acceptCharset(StandardCharsets.UTF_8)
                                .retrieve()
                                .toEntity(MyResponse.class)
                                .flatMap(entity -> Mono.justOrEmpty(entity.getHeaders().getFirst("content-type")));
Object rs = mono.block();
public class MyResponse {
 Object body;
 Integer status;
 String contentType;
}

CodePudding user response:

I would like to receive the headers (especially the content-type) from the webclient response

Generally speaking you can access response headers like this:

ResponseEntity<MyResponse> response = webClient.get()
        .uri(path)
        .acceptCharset(StandardCharsets.UTF_8)
        .retrieve()
        .toEntity(MyResponse.class)
        .block();
HttpHeaders headers = response.getHeaders();
MediaType contentType = headers.getContentType();

But from the error you pasted it appears that you are accessing an image (image/tiff) that obviously cannot be converted to your MyResponse class.

  • Related