Spring 3.x JSON status 406“特性不可接受根据请求“接受”标头()”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12865093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring 3.x JSON status 406 "characteristics not acceptable according to the request "accept" headers ()"
提问by user1740567
Upon trying to get my response in JSONusing Spring 3.x, I get the 406 error"The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request"accept" headers ()."
尝试在JSONusing 中获得响应时Spring 3.x,我得到406 error“此请求标识的资源只能生成具有根据request“接受”标头 ()不可接受的特征的响应。
Here is my environment
这是我的环境
* Spring 3.2.0.RELEASE
* included Hymanson-mapper-asl-1.7.9.jar, Hymanson-core-asl-1.7.9.jar
* Tomcat 6.x
* mvc:annotation-driven in Spring configuration XML file
My Controller:
我的控制器:
@RequestMapping("/contest")
public class ContestController {
@RequestMapping(value="{name}", headers="Accept=*/*", method = RequestMethod.GET)
public @ResponseBody Contest getContestInJSON(@PathVariable String name) {
Contest contest = new Contest();
contest.setName(name);
contest.setStaffName(new String("contestitem1"));
return contest;
}
}
My Spring Configuration file
我的 Spring 配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.contestframework.controllers" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingHymansonJsonView" />
</list>
</property>
</bean>
<mvc:annotation-driven />
</beans>
After this I just access the Controller using below:
在此之后,我只需使用以下方法访问控制器:
http://domain/SpringWebProject/json/contest/abcd
and the response I get is Status 406: "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()."
我得到的响应是状态 406:“此请求标识的资源只能生成具有根据请求“接受”标头 () 不可接受的特征的响应。
I also tried an alternate mechanism by access this using JavascriptAJAXto make sure my request header has application/JSONbut this led to the same Status 406 result
我还尝试了一种替代机制,通过访问它JavascriptAJAX来确保我的请求标头具有,application/JSON但这导致了相同的状态 406 结果
$.getJSON('contest/abcd', function(data) {
console.log(data) }
Here is my REQUEST HEADER captured from browser:
这是我从浏览器捕获的请求头:
Request URL:http://localhost:8080/SpringWebProject/json/contest/abcd
Request Method:GET
Status Code:406 Not Acceptable
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:JSESSIONID=59689C95B0B9C21494EB0AB9D9F7BCCD
Host:localhost:8080
Referer:http://localhost:8080/SpringWebProject/json/welcome
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4
X-Requested-With:XMLHttpRequest
Response Headersview source
Content-Length:1070
Content-Type:text/html;charset=utf-8
Date:Fri, 12 Oct 2012 18:23:40 GMT
Server:Apache-Coyote/1.1
Appreciate any help in this regard.
感谢这方面的任何帮助。
采纳答案by Biju Kunjummen
There is nothing wrong in your configuration, let me suggest a few small changes though:
您的配置没有任何问题,但让我建议一些小的更改:
a) Your namespaces appear wrong - they are referring to the 3.0 schemas, just change them to either 3.1 one's or don't refer to the version explicitly, this way for eg.
a) 您的命名空间似乎是错误的 - 它们指的是 3.0 模式,只需将它们更改为 3.1 或不显式指代版本,例如这种方式。
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
OR
或者
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
b) You don't require the ContentNegotiatingViewResolver, you can remove everything but the component-scanand <mvc:annotation-driven/>from your configuration
b)你不需要ContentNegotiatingViewResolver,可以去除一切,但component-scan并<mvc:annotation-driven/>从配置
c) The request will not directly work from the browser as it explicitly requires an Accept header of "application/json" - $.getJsoncall should work though as it sends the correct headers
c) 该请求不会直接从浏览器工作,因为它明确需要“application/json”的 Accept 标头 -$.getJson调用应该可以工作,因为它发送了正确的标头
d) Remove the headers=Acc..from the @RequestMapping, and produces also, both are filtering criteria to match up the correct mapped method call.
d)headers=Acc..从@RequestMapping 中删除,并产生,两者都是匹配正确映射方法调用的过滤条件。
With these, there is no reason why the json should not get served out, can you please try with these and see how it goes.
有了这些,就没有理由不提供 json 了,你能不能试试这些,看看效果如何。
回答by annihilate
I have also just experienced this same issue. It would appear it is an issue with the latest 3.2.0.RELEASE, as I previously had 3.1.2.RELEASE and it all worked. After changing to 3.2.0.RELEASE it breaks. Have tested with 3.1.3.RELEASE and that works fine. So for now I would suggest rolling back to 3.1.3.RELEASE
我也刚刚遇到了同样的问题。看起来这是最新的 3.2.0.RELEASE 的问题,因为我以前有 3.1.2.RELEASE 并且一切正常。更改为 3.2.0.RELEASE 后,它会中断。已经用 3.1.3.RELEASE 测试过,效果很好。所以现在我建议回滚到 3.1.3.RELEASE
EDIT: Thanks to another post on this site that linked to the following location: http://static.springsource.org/spring-framework/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-config-content-negotiation
编辑:感谢本网站上链接到以下位置的另一篇文章:http: //static.springsource.org/spring-framework/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-配置内容协商
I've now got it working by disabling the getting of media type based on the extension of the requested path. This can be done by the following:
我现在通过根据请求路径的扩展禁用获取媒体类型来让它工作。这可以通过以下方式完成:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- Turn off working out content type based on URL file extension, should fall back to looking at the Accept headers -->
<property name="favorPathExtension" value="false" />
</bean>
And specify version 3.2 for all the xsd schema locations.
并为所有 xsd 架构位置指定版本 3.2。
And this is using the following Hymanson jars:
这是使用以下Hyman逊罐子:
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-core</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.1.2</version>
</dependency>
回答by Anupam Pawar
I had the same problem and I solved it by adding following dependency
我遇到了同样的问题,我通过添加以下依赖项解决了它
<dependency>
<groupId>org.codehaus.Hymanson</groupId>
<artifactId>Hymanson-mapper-asl</artifactId>
<version>${Hymanson.version}</version>
</dependency>
Previously I'm doing it with following dependency
以前我是用以下依赖来做的
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-core</artifactId>
<version>${com.Hymanson.core-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-annotations</artifactId>
<version>${com.Hymanson.core-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>${com.Hymanson.core-version}</version>
</dependency>
In short I have replace com.fasterxml.Hymanson.core by org.codehaus.Hymanson
简而言之,我已将 com.fasterxml.Hymanson.core 替换为org.codehaus.Hymanson
回答by Weslei Prudencio
I had this problem in Spring MVC 4. Adding Hymanson-annotations, Hymanson-core and Hymanson-databind didn't solve the problem. Try this libs:
我在 Spring MVC 4 中遇到了这个问题。添加 Hymanson-annotations、Hymanson-core 和 Hymanson-databind 并没有解决问题。试试这个库:
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-core</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.Hymanson</groupId>
<artifactId>Hymanson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
回答by les2
I think you need to add a produces="application/json" to your @RequestMapping (haven't looked at spring mvc in a while so i'm not 100% positive) ...
我认为你需要在 @RequestMapping 中添加一个 products="application/json"(有一段时间没看过 spring mvc,所以我不是 100% 肯定的)......
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
16.3.2.6 Producible Media Types
You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the produces condition. For example:
16.3.2.6 可生产媒体类型
您可以通过指定可生产的媒体类型列表来缩小主要映射的范围。只有当 Accept 请求标头与这些值之一匹配时,才会匹配请求。此外,生产条件的使用确保用于生成响应的实际内容类型尊重生产条件中指定的媒体类型。例如:
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
回答by OscarRyz
I had the same problem and the comment added by Biju Kunjummen in this answer worked for me perfectly
我遇到了同样的问题,Biju Kunjummen 在这个答案中添加的评论对我来说非常有用
https://stackoverflow.com/a/12873170/20654
https://stackoverflow.com/a/12873170/20654
That is have public getters in my Java class
那是在我的 Java 类中有公共 getter
回答by burcakulug
I had a similar problem, it got resolved when I added Hymanson-databindlibrary.
我有一个类似的问题,当我添加Hymanson-databind库时它得到了解决。
These are my dependencies:
这些是我的依赖项:
<dependency>
<groupId>org.codehaus.Hymanson</groupId>
<artifactId>Hymanson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.4.3</version>
</dependency>
回答by Steven Neiner
Don't make the same mistake I did, spend all day playing around with Spring configuration, when actually your object returned in a web service is not marshaling to XML correctly. It seems Spring catches a JAXB marshaling error and doesn't report it. Use this sandbox code to validate JAXB marshaling:
不要犯和我一样的错误,一整天都在玩 Spring 配置,而实际上您在 Web 服务中返回的对象没有正确地封送至 XML。似乎 Spring 捕获了 JAXB 封送处理错误并且没有报告它。使用此沙箱代码验证 JAXB 封送处理:
MyClass myclass = new MyClass();
//populate myclass here
JAXBContext context = JAXBContext.newInstance(MyClass.class);
Marshaller m = context.createMarshaller();
StringWriter w = new StringWriter();
m.marshal(myclass, w);
System.out.println(w);
This produced and displayed an exception. Fixed the cause, and my web service is available in both XML and JSON.
这产生并显示异常。修复了原因,我的 Web 服务在 XML 和 JSON 中都可用。
回答by Vikram Thakur
Thank you for sharing you experience.I experienced the same problem and it works for me using configuration as show below:
感谢您分享您的经验。我遇到了同样的问题,使用如下所示的配置对我有用:
- Spring MVC Version : 3.2.5.RELEASE
- Apache-tomcat-6.0.24
- JDK1.6
- Hymanson-core-asl-1.9.10.jar
- Hymanson-mapper-asl-1.9.10.jar
- Spring MVC 版本:3.2.5.RELEASE
- Apache-tomcat-6.0.24
- JDK1.6
- Hymanson-core-asl-1.9.10.jar
- Hymanson-mapper-asl-1.9.10.jar
Spring MVC Config File:
Spring MVC 配置文件:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- Turn off working out content type based on URL file extension, should fall back to looking at the Accept headers -->
<property name="favorPathExtension" value="false" />
</bean>
Model class : Country.java
模型类:Country.java
private Integer countryId;
private String name;
//public setters and getters
Controller Method:
控制器方法:
@RequestMapping(value = "/get_country_json",method = RequestMethod.GET)
@ResponseBody
public Country getCountry()
Deployment Descriptor(web.xml)
部署描述符(web.xml)
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
URL Requested to call controller method: /SpringCURDApp/get_country_json.htm
请求调用控制器方法的 URL:/SpringCURDApp/get_country_json.htm
I hope this can help someone.
我希望这可以帮助某人。
回答by Sergii Shevchyk
Shortly:
不久:
For Spring MVC 4.1.6 there is enough:
对于 Spring MVC 4.1.6,有足够的:
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.5.0</version>
</dependency>
Hymanson-databindhas dependency on coreand annotationsartifacts.
Hymanson-databind依赖于核心和注释工件。
In details:
详细说明:
What is HTTP 406error?
什么是HTTP 406错误?
406 Not Acceptable The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.
406 Not Acceptable 请求的资源只能根据请求中发送的Accept头生成不可接受的内容。
It means that Server cannot generate content which MEDIA TYPEstated in AcceptHeader.
这意味着服务器不能生成接受头中规定的媒体类型的内容。
But how does server know which MEDIA TYPEit can generate and which not?
但是服务器如何知道它可以生成哪些媒体类型,哪些不能?
Spring Web has concept of HttpMessageConverter. Some of these converters are already registered in Spring and AbstractMessageConverterMethodArgumentResolverholds them in property messageConverters.
Spring Web 有HttpMessageConverter 的概念。其中一些转换器已经在 Spring 中注册,并且AbstractMessageConverterMethodArgumentResolver将它们保存在属性messageConverters 中。
During request processing AbstractMessageConverterMethodProcessoranalyzes what spring can convert and saves all supported MEDIA TYPESin producibleMediaTypesvariable. If requested MEDIA TYPEis not producible then says Error 406 == I cannot generated requested media type. Sorry.
在请求处理期间,AbstractMessageConverterMethodProcessor分析 spring 可以转换的内容并将所有支持的MEDIA TYPES保存在producibleMediaTypes变量中。如果请求的媒体类型不可生成,则显示错误 406 == 我无法生成请求的媒体类型。对不起。
To cut the long story short - register required converters. In your case it's Hymanson library which produces application/json
长话短说 - 注册所需的转换器。在您的情况下,它是生成application/json的 Hymanson 库

