Spring Boot 406(type=Not Acceptable, status=406)異常解決辦法

使用Spring Boot,Controller請求返回的參數類型是ResponseBody , 若是請求的時候使用使用配置的默認請求擴展名,例如.html,Spring MVC會拋出一個type=Not Acceptable, status=406錯誤,以下:html

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Jan 23 17:14:35 CST 2017
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation

請求處理的Controller代碼以下:java

/**
     * 延時獲取用戶端瀏覽器的跟蹤ID
     * @param request
     * @param response
     * @param orgi
     * @param appid
     * @param userid
     * @param sign
     * @return
     */
    @RequestMapping("/online")
    @Menu(type = "im" , subtype = "online" , access = true)
    public @ResponseBody OnlineUser online(HttpServletRequest request , HttpServletResponse response , @Valid String orgi , @Valid String appid, @Valid String userid , @Valid String sign){
    	OnlineUser onlineUser = null ;
    	if(!StringUtils.isBlank(sign)){
    		onlineUser = OnlineUserUtils.online(super.getIMUser(request , sign) , orgi ,sign , UKDataContext.OnlineUserTypeStatus.WEBIM.toString(), request);
    	}
    	return onlineUser;
    }

處理辦法:json

一、使用JSON請求Controller,增長 org.codehaus.jackson  的依賴瀏覽器

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

請求的URL使用http://xxx.xxx.xxx.xxx:8080/online.json,訪問正常。app

二、覆蓋Application.java裏的 configureContentNegotiation  方法,代碼以下:ide

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter {
   
  
    @Override
   public void configureContentNegotiation(ContentNegotiationConfigurer config) {
        config.favorPathExtension(false);
    }
    public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
    }
}

方法2中關鍵的代碼在於 config.favorPathExtension(false);this

favorPathExtension表示支持後綴匹配,
ignoreAcceptHeader默認爲fasle,表示accept-header匹配,defaultContentType開啓默認匹配。spa

相關文章
相關標籤/搜索