【问题标题】:SpringCloud OpenFeign: consume response with content type text/htmlSpringCloud OpenFeign:使用内容类型为 text/html 的响应
【发布时间】:2021-11-19 09:03:52
【问题描述】:

我正在使用 SpringCloud openfeign 调用另一个不属于我们团队的微服务。 当我定义这个 feignclient 时。

@FeignClient(name="test, url="/test")
public interface MyFeignClient {
 
  @GetMapping("/hello)
  MyCustomRespone getValuesFromOtherService(@RequestParam String name, @RequestParam int id);
}

调用时出现异常:Spring Feign:无法提取响应:没有找到适合响应类型的HttpMessageConverter

然后我尝试从io.github.openfeign添加feign-jackson

<dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-jackson</artifactId>
</dependency>

但它仍然显示相同的异常。 然后我注意到我调用的其余api返回的上下文类型是“text/html”。我可以使用ObjectMapper进行分析,但这似乎不是一个好方法它。

那么有没有办法解决这个问题,注意我不能修改不属于out team的api。

【问题讨论】:

  • 那你想做什么?将 html 响应转换为 Java 对象?

标签: spring-boot microservices spring-cloud rest openfeign


【解决方案1】:

由于您在调用 api 时收到了 html 类型的响应,因此您需要为此编写自定义的 httpMessageConverter。另外请确保更新支持的媒体类型: super.setSupportedMediaTypes(types);请参考:https://www.javadevjournal.com/spring/spring-http-message-converter/ 您还可以尝试将消息提取为字符串并使用 Gson 转换器。例如:GsonHttpMessageConverter

public class CustomHttpMessageConverter extends GsonHttpMessageConverter {
public MyGsonHttpMessageConverter() {
    List<MediaType> types = Arrays.asList(
            new MediaType("text", "html", DEFAULT_CHARSET)
    );
    super.setSupportedMediaTypes(types);
}

}

【讨论】:

    【解决方案2】:

    我遇到了完全相同的问题,我通过创建一个使用 Jackson 的自定义解码器解决了这个问题

    @Bean
    public Decoder feignDecoder() {
        return (response, type) -> {
            String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
            JavaType javaType = TypeFactory.defaultInstance().constructType(type);
            return new ObjectMapper().readValue(bodyStr, javaType);
        };
    }
    

    然后我配置了 feign 来使用这个配置。

    @FeignClient(url = "https://myurl.com", name = "client-name", configuration = FeignCustomConfiguration.class)
    

    【讨论】:

      猜你喜欢
      • 2015-04-19
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多