SpringBoot之RestTemplate 406问题完美解决

SpringBoot提供了一个强大的访问外部接口的工具类RestTemplate,依赖注入spring-boot-starter-web 会自带。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

这个工具类是针对Resetful API风格的,其实这个风格是2000年一个博士论文中提出的。

在使用过程中出现了一个让我头疼的问题,一直报org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation,错误码是406。

找了半天,终于解决了这个问题。

解决方案:

(1)在启动类App.java类中继承:WebMvcConfigurerAdapter

(2)覆盖方法:configureContentNegotiation

@SpringBootApplication

public class ApiCoreApp extends WebMvcConfigurerAdapter {

   

    /**

     (1)在启动类App.java类中继承:WebMvcConfigurerAdapter

    (2)覆盖方法:configureContentNegotiation

   

    favorPathExtension表示支持后缀匹配,

    属性ignoreAcceptHeader默认为fasle,表示accept-header匹配,defaultContentType开启默认匹配。

       例如:请求aaa.xx,若设置<entry key="xx" value="application/xml"/> 也能匹配以xml返回。

根据以上条件进行一一匹配最终,得到相关并符合的策略初始化ContentNegotiationManager  

     */

    @Override

   public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {

        configurer.favorPathExtension(false);

    }

    public static void main(String[] args) {

       SpringApplication.run(ApiCoreApp.class, args);

    }

}

核心代码是 configurer.favorPathExtension(false);表示支持后缀匹配。然后这个问题就神奇的解决了。

这个406的问题,其实就是远程API服务器找不到可以接收的对象,也就是我返回的数据,你没办法接收。

感谢大佬的帮助,

https://412887952-qq-com.iteye.com/blog/2315133

posted @ 2019-02-28 18:51  TroubleBoy丶  阅读(1022)  评论(0)    收藏  举报