首页 > 解决方案 > 使用 Spring Boot 2 WebClient 从响应中获取标头

问题描述

我想从 webclient 响应中接收标头(尤其是内容类型)。我用 flatmap-mono-getHeaders 找到了这段代码,但它不起作用。

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

我该如何解决?或者也许有人可以推荐一个更简单的解决方案。

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

标签: javaspringspring-bootspring-mvcspring-webflux

解决方案


我想从 webclient 响应中接收标头(尤其是内容类型)

一般来说,您可以像这样访问响应标头:

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

但是从您粘贴的错误看来,您正在访问的图像 ( image/tiff) 显然无法转换为您的MyResponse类。


推荐阅读