java - Spring JSON请求获得406(不可接受)
这是我的javascript:
function getWeather() {
$.getJSON('getTemperature/' + $('.data option:selected').val(), null, function(data) {
alert('Success');
});
}
这是我的控制器:
@RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)
@ResponseBody
public Weather getTemparature(@PathVariable("id") Integer id){
Weather weather = weatherService.getCurrentWeather(id);
return weather;
}
为spring-servlet.xml
得到此错误:
GET http://localhost:8080/web/getTemperature/2 406 (Not Acceptable)
头:
响应标题
Server Apache-Coyote/1.1
Content-Type text/html;charset=utf-8
Content-Length 1070
Date Sun, 18 Sep 2011 17:00:35 GMT
请求标题
Host localhost:8080
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
Accept application/json, text/javascript, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/web/weather
Cookie JSESSIONID=7D27FAC18050ED84B58DAFB0A51CB7E4
有趣的说明:
我得到406错误,但hibernate查询同时工作。这是tomcat日志所说的,每当我更改dropbox中的选择时:
select weather0_.ID as ID0_0_, weather0_.CITY_ID as CITY2_0_0_, weather0_.DATE as DATE0_0_, weather0_.TEMP as TEMP0_0_ from WEATHER weather0_ where weather0_.ID=?
问题是什么? 在之前有两个类似的问题,我尝试了所有接受的提示,但我认为它们不起作用......
有什么建议? 随意问的问题...
21个解决方案
101 votes
406不可接受
由请求标识的资源仅能够根据请求中发送的接受报头生成具有不可接受的内容特征的响应实体。
因此,您的请求接受标头是application / json,您的控制器无法返回该标头。 当无法找到正确的HTTPMessageConverter来满足@ResponseBody带注释的返回值时,会发生这种情况。 在类路径中给定某些3-d方库时,使用headers="Accept=*/*"时会自动注册HTTPMessageConverter。
您在类路径中没有正确的杰克逊库,或者您没有使用过headers="Accept=*/*"指令。
我成功地复制了你的场景,并且使用这两个库并且没有headers="Accept=*/*"指令它工作正常。
杰克逊核心ASL-1.7.4.jar
杰克逊映射器-ASL-1.7.4.jar
Villu Sepman answered 2019-05-05T16:21:18Z
71 votes
我有同样的问题,从最新的Spring 4.1.1开始,你需要将以下jar添加到pom.xml。
com.fasterxml.jackson.core
jackson-core
2.4.1
com.fasterxml.jackson.core
jackson-databind
2.4.1.1
还要确保你有以下jar:
org.codehaus.jackson
jackson-core-asl
1.9.13
org.codehaus.jackson
jackson-mapper-asl
1.9.13
406 Spring MVC Json,根据请求“接受”标题不可接受
bekur answered 2019-05-05T16:21:57Z
15 votes
还有另一种情况会返回此状态:如果Jackson映射器无法弄清楚如何序列化bean。 例如,如果对于相同的布尔属性有两个访问器方法,则为StdSerializerProvider._createAndCacheUntypedSerializer和JsonMappingException。
发生的事情是Spring的MappingJackson2HttpMessageConverter调用Jackson的StdSerializerProvider来查看它是否可以转换你的对象。 在通话链的底部,StdSerializerProvider._createAndCacheUntypedSerializer抛出JsonMappingException,其中包含一条信息性消息。 但是,这个异常被StdSerializerProvider._createAndCacheUntypedSerializer吞噬,它告诉Spring它无法转换对象。 由于转换器耗尽,Spring报告说它没有得到它可以使用的Accept标题,当你给它*/*时当然是假的。
这种行为有一个错误,但它被关闭为“无法重现”:被调用的方法没有声明它可以抛出,因此吞咽异常显然是一个合适的解决方案(是的,这是讽刺)。 不幸的是,杰克逊没有任何记录......并且在代码库中有很多评论希望它能做到,所以我怀疑这不是唯一隐藏的问题。
kdgregory answered 2019-05-05T16:22:39Z
13 votes
我有同样的问题,我的控制器方法执行但响应是错误406。我调试AbstractMessageConverterMethodProcessor#writeWithMessageConverters,发现方法ContentNegotiationManager#resolveMediaTypes总是返回text/html,MappingJacksonHttpMessageConverter不支持。问题是org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy的工作时间早于org.springframework.web.accept.HeaderContentNegotiationStrategy,我的请求扩展/get-clients.html是我的错误406问题的原因。我刚刚更改了请求网址 至/get-clients。
atott answered 2019-05-05T16:23:07Z
9 votes
确保在类路径中存在以下2 jar。
如果缺少任何一个或两个,则会出现此错误。
jackson-core-asl-1.9.X.jar jackson-mapper-asl-1.9.X.jar
Raju Rathi answered 2019-05-05T16:23:42Z
5 votes
终于从这里找到了答案:
将restful ajax请求映射到spring
我引用:
@RequestBody / @ ResponseBody注释不使用普通的视图解析器,它们使用自己的HttpMessageConverters。 为了使用这些注释,您应该在AnnotationMethodHandlerAdapter中配置这些转换器,如引用中所述(您可能需要MappingJacksonHttpMessageConverter)。
Jaanus answered 2019-05-05T16:24:28Z
3 votes
检查dispatcherservlet.xml中的,如果没有添加它。并添加
org.codehaus.jackson
jackson-core-asl
1.9.13
org.codehaus.jackson
jackson-mapper-asl
1.9.13
你的pom.xml中的这些依赖项
SHIVA answered 2019-05-05T16:25:03Z
2 votes
com.fasterxml.jackson.jaxrs
jackson-jaxrs-base
2.6.3
Rajan answered 2019-05-05T16:25:25Z
1 votes
在控制器中,响应体注释不应该在返回类型而不是方法上,如下所示:
@RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)
public @ResponseBody Weather getTemparature(@PathVariable("id") Integer id){
Weather weather = weatherService.getCurrentWeather(id);
return weather;
}
我还使用原始的jquery.ajax函数,并确保正确设置了contentType和dataType。
换句话说,我发现json的弹簧处理相当有问题。 当我使用字符串和GSON完成所有操作时更容易。
NimChimpsky answered 2019-05-05T16:26:09Z
1 votes
我遇到了同样的问题,因为我错过了@EnableMvc注释。 (我的所有Spring配置都是基于注释的,XML等价物将是mvc:annotation-driven)
jambriz answered 2019-05-05T16:26:39Z
1 votes
正如@atott所说。
如果你已经在你的pom.xml中添加了最新版本的Jackson,并且在你的动作方法上使用了233431328567328870,在你的动作方法中使用了233431328567328870,那么你仍然得到了406(不可接受),我想你需要 在MVC DispatcherServlet上下文配置中尝试此操作:
这就是我最终解决问题的方式。
Raven answered 2019-05-05T16:27:23Z
1 votes
Spring 4.3.10:我使用以下设置来解决问题。
第1步:添加以下依赖项
com.fasterxml.jackson.core
jackson-core
2.6.7
com.fasterxml.jackson.core
jackson-databind
2.6.7
org.codehaus.jackson
jackson-core-asl
1.9.13
org.codehaus.jackson
jackson-mapper-asl
1.9.13
第2步:在MVC DispatcherServlet上下文配置中添加以下内容:
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
从Spring 3.2开始,按照默认配置将favorPathExtension设置为true,因为如果请求uri有任何适当的扩展名,如.htm spring将优先扩展。 在第2步中,我添加了contentNegotiationManager bean来覆盖它。
Kevin Sebastian Fernandez answered 2019-05-05T16:28:14Z
1 votes
可能没有人向下滚动这一点,但上述解决方案都没有为我修复它,但制作了所有我的getter方法public。
我把我的getter知名度保留在package-private; 杰克逊决定找不到它们并且爆炸了。 (使用@JsonAutoDetect(getterVisibility=NON_PRIVATE)仅部分修复它。
Hazel Troost answered 2019-05-05T16:28:52Z
0 votes
确保你的类路径中有正确的jackson版本
joyfun answered 2019-05-05T16:29:23Z
0 votes
检查为@joyfun做了正确的杰克逊版本,但也检查我们的标题...接受/可能不是由客户端传输...使用firebug或等效的检查您的获取请求实际发送的内容。 我认为注释的头属性/可能/正在检查文字虽然我不是100%肯定。
Dave G answered 2019-05-05T16:29:56Z
0 votes
除了包含Spring servlet中所有可能的JAR,依赖项和注释之外,我还有一个我无法解决的明显问题。 最终我发现我有错误的文件扩展名,我的意思是我有两个单独的servlet在同一个容器中运行,我需要映射到不同的文件扩展名,其中一个是“.do”,另一个用于订阅,随机命名为“。子”。 所有好,但SUB是通常用于电影字幕文件的有效文件扩展名,因此Tomcat覆盖了标题并返回类似“text / x-dvd.sub ...”的内容所以一切都很好,但应用程序期待JSON但获得字幕 因此我所要做的就是更改我添加的web.xml文件中的映射:
sub
application/json
infinity answered 2019-05-05T16:30:29Z
0 votes
我有同样的问题,遗憾的是,这里没有解决方案解决了我的问题,因为我的问题是在另一个班级。
我首先检查了@bekur建议的所有依赖关系然后我检查了从客户端传送到服务器的请求/响应所有头文件都是由Jquery正确设置的。然后我检查了RequestMappingHandlerAdapter MessageConverters并且所有7个都到位了,我真的开始讨厌春天了! 然后我更新到Spring 4.0.6.RELEASE到4.2.0.RELEASE我得到了另一个响应而不是上面的响应。 这是Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type
这是我的控制器方法
@RequestMapping(value = "/upload", method = RequestMethod.POST,produces = "application/json")
public ResponseEntity pictureUpload(FirewalledRequest initialRequest) {
DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) initialRequest.getRequest();
try {
Iterator iterator = request.getFileNames();
while (iterator.hasNext()) {
MultipartFile file = request.getFile(iterator.next());
session.save(toImage(file));
}
} catch (Exception e) {
return new ResponseEntity(new UploadPictureResult(),HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity(new UploadPictureResult(), HttpStatus.OK);
}
public class UploadPictureResult extends WebResponse{
private List images;
public void setImages(List images) {
this.images = images;
}
}
public class WebResponse implements Serializable {
protected String message;
public WebResponse() {
}
public WebResponse(String message) {
this.message = message;
}
public void setMessage(String message) {
this.message = message;
}
}
解决方案是使UploadPictureResult不扩展WebResponse
出于某种原因,Spring在扩展WebResponse时无法确定如何转换UploadPictureReslt
Adelin answered 2019-05-05T16:31:31Z
0 votes
com.fasterxml.jackson.core
jackson-databind
2.8.0
我不使用ssl身份验证,这个jackson-databind包含jackson-core.jar和jackson-databind.jar,然后更改RequestMapping内容,如下所示:
@RequestMapping(value = "/id/{number}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
public @ResponseBody Customer findCustomer(@PathVariable int number){
Customer result = customerService.findById(number);
return result;
}
注意:如果你的产品不是“application / json”类型,我没有注意到这个并得到406错误,帮助这可以帮助你。
Crabime answered 2019-05-05T16:32:11Z
0 votes
检查这个帖子。spring mvc restcontroller返回json字符串p / s:你应该将jack子映射配置添加到你的WebMvcConfig类
@Override
protected void configureMessageConverters(
List> converters) {
// put the jackson converter to the front of the list so that application/json content-type strings will be treated as JSON
converters.add(new MappingJackson2HttpMessageConverter());
// and probably needs a string converter too for text/plain content-type strings to be properly handled
converters.add(new StringHttpMessageConverter());
}
Anh Lam answered 2019-05-05T16:32:49Z
0 votes
这是springVersion = 5.0.3.RELEASE的更新答案。
以上答案将只适用于年龄较大的springVersion< 4.1版本。 对于最新的spring,您必须在gradle文件中添加以下依赖项:
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: fasterxmljackson
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: fasterxmljackson
fasterxmljackson=2.9.4
我希望这对使用最新弹簧版本的人有所帮助。
-3 votes
你可以删除@RequestMapping中的headers元素并尝试..
喜欢
我猜spring是一个'包含检查',而不是接受标题的完全匹配。 但仍然值得尝试删除header元素并检查。
stratwine answered 2019-05-05T16:34:19Z