【问题标题】:WebClient - UnsupportedMediaTypeExceptionWebClient - UnsupportedMediaTypeException
【发布时间】:2021-10-14 14:55:30
【问题描述】:

我有这个代码:

ResponseEntity<DTODemo> responseEntity = webClient.get()
                .uri("http://localhost:8051/callAPI/")
                .retrieve()
                .toEntity(DTODemo.class)
                .block();

当我的 api 返回一个对象 DTODemo 时,它起作用了。 但是,API 可以在正文中返回带有代码 HTTP 404 的消息(类型 String)。 我有这个例外:

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/plain;charset=UTF-8' not supported for bodyType=com.example.demo.DTODemo 

我尝试了很多方法,但没有找到好的解决方案。

有没有办法使用 retrieve 而不是 exchange 来解决我的问题?

非常感谢。

【问题讨论】:

  • 使用retrieve(),除了正文之外,您无法访问任何响应信息。因此,没有办法以简单的方式处理“坏”场景。真的禁止使用exchange()吗?
  • stackoverflow.com/a/67471061 - 有帮助吗?
  • 因为在 Spring 中现在不推荐使用交换。
  • 我找到了这个代码的解决方案:.onErrorResume(WebClientResponseException.class, ex -> { ex.getResponseBodyAsString(); return Mono.empty(); })

标签: java spring spring-webclient


【解决方案1】:

您可以指定一组可接受的媒体类型,由 Accept 标头指定。例如,

ResponseEntity<DTODemo> responseEntity = webClient.get()
                .uri("http://localhost:8051/callAPI/")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .toEntity(DTODemo.class)
                .block();

【讨论】:

    猜你喜欢
    • 2020-08-02
    • 1970-01-01
    • 2015-10-06
    • 2012-05-06
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    相关资源
    最近更新 更多