【问题标题】:Get headers from response with Spring Boot 2 WebClient使用 Spring Boot 2 WebClient 从响应中获取标头
【发布时间】:2021-11-15 20:31:55
【问题描述】:

我想从 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;
}

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-webflux


    【解决方案1】:

    我想从 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 类。

    【讨论】:

    • 是的,响应是图像。如果没有必要,我不想将响应转换为类。这是我发现的唯一有用的例子,这就是我尝试它的原因。我只想要标题内容类型。那么如果响应是图像,就没有办法获取标题吗?如果我使用 .get().uri().retrieve() 和一些 onStatus() ,我会得到没有 .getHeaders() 的 ResponseSpec。
    • 如果您只对响应标头感兴趣,您可以执行HEAD 请求而不是GET。您也可以使用.toBodilessEntity() 代替.toEntity(MyResponse.class)
    • 谢谢!它几乎可以工作。我尝试使用 .toEntity( String.class ) ,我也收到了标题和图像。但是当我写入文件时,字符串,字符与真实 tif 图像中的字符不同,我无法打开文件。我也尝试使用 .toEntity( MultipartFile ),但它再次“不支持”。也许我可以将它称为 Multipart 以外的其他名称?还是字符编码错误?
    • 看来,标准字符很好(a、b、c...),但“原始 tiff”图像有 'm=p`¶ŕ¸żĂh ' 和 'w˙ü/ ˙Č' 字符,我在回复中没有。我只是有矩形....我将 UTF_8 更改为 UTF_16BE 和 ISO_8859_1 ,但结果是一样的。
    • 试试.toEntity(byte[].class)
    猜你喜欢
    • 2018-10-31
    • 1970-01-01
    • 2020-10-30
    • 2019-05-17
    • 1970-01-01
    • 2017-03-21
    • 2017-07-07
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多