Spring JSON请求获得406(不可接受)

问题描述 投票:78回答:22

这是我的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

<context:annotation-config />
<tx:annotation-driven />

得到此错误:

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=?

问题是什么?在之前有两个类似的问题,我尝试了所有接受的提示,但我认为它们不起作用......

有什么建议?随意问的问题...

java javascript ajax json spring
22个回答
103
投票

406不可接受

由请求标识的资源仅能够根据请求中发送的接受报头生成具有不可接受的内容特征的响应实体。

因此,您的请求接受标头是application / json,您的控制器无法返回该标头。当无法找到正确的HTTPMessageConverter来满足@ResponseBody带注释的返回值时,会发生这种情况。在类路径中给定某些3-d方库时,使用<mvc:annotation-driven>时会自动注册HTTPMessageConverter。

您在类路径中没有正确的Jackson库,或者您没有使用<mvc:annotation-driven>指令。

我成功地复制了你的场景,并且使用这两个库并且没有headers="Accept=*/*"指令它运行良好。

  • 杰克逊核心最174yara
  • 杰克逊尺寸最174yara

1
投票

我遇到了同样的问题,因为我错过了@EnableMvc注释。 (我的所有Spring配置都是基于注释的,XML等价物将是mvc:annotation-driven)


1
投票

作为@atott mentioned

如果你已经在你的pom.xml中添加了最新版本的Jackson,并且使用了Spring 4.0或更新版本,在你的动作方法上使用了@ResponseBody,而在@RequestMapping中配置了produces="application/json;charset=utf-8",那么你仍然有406(不可接受),我想你需要在MVC DispatcherServlet上下文配置中尝试此操作:

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
</bean>

这就是我最终解决问题的方式。


1
投票

Spring 4.3.10:我使用以下设置来解决问题。

第1步:添加以下依赖项

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.6.7</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.7</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

第2步:在MVC DispatcherServlet上下文配置中添加以下内容:

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>

<bean id="contentNegotiationManager"
    class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false"/>
    <property name="favorParameter" value="true"/>
    <property name="ignoreAcceptHeader" value="false" />
</bean>

从Spring 3.2开始,按照默认配置将favorPathExtension设置为true,因为如果请求uri有任何适当的扩展,如.htm spring将优先扩展。在第2步中,我添加了contentNegotiationManager bean来覆盖它。


1
投票

可能没有人向下滚动这一点,但上述解决方案都没有为我修复它,但是制作了所有我的getter方法public

我把我的getter知名度保留在package-private;杰克逊决定找不到它们并且爆炸了。 (使用@JsonAutoDetect(getterVisibility=NON_PRIVATE)只能部分修复它。


0
投票

确保你的类路径中有正确的jackson版本


0
投票

检查为@joyfun做了正确的杰克逊版本,但也检查我们的标题...接受/可能不是由客户端传输...使用firebug或等效的检查您的获取请求实际发送的内容。我认为注释的头属性/可能/正在检查文字虽然我不是100%肯定。


0
投票

除了包含Spring servlet中所有可能的JAR,依赖项和注释之外,我还有一个我无法解决的明显问题。最终我发现我有错误的文件扩展名,我的意思是我有两个单独的servlet在同一个容器中运行,我需要映射到不同的文件扩展名,其中一个是“.do”,另一个用于订阅,随机命名为“。子”。所有好,但SUB是通常用于电影字幕文件的有效文件扩展名,因此Tomcat覆盖了标题并返回类似“text / x-dvd.sub ...”的内容所以一切都很好,但应用程序期待JSON但获得字幕因此,我所要做的就是更改我添加的web.xml文件中的映射:

<mime-mapping>
    <extension>sub</extension>
    <mime-type>application/json</mime-type>
</mime-mapping>

0
投票

我有同样的问题,遗憾的是,这里没有解决方案解决了我的问题,因为我的问题是在另一个班级。

我首先检查所有依赖关系是否已按照@bekur的建议到位,然后我检查了从客户端传输到服务器的请求/响应所有标头都已由Jquery正确设置。然后我检查了RequestMappingHandlerAdapter MessageConverters并且所有7个都到位了,我真的开始讨厌Spring了!然后我更新到Spring 4.0.6.RELEASE4.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<UploadPictureResult> pictureUpload(FirewalledRequest initialRequest) {

        DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) initialRequest.getRequest();

        try {
            Iterator<String> iterator = request.getFileNames();

            while (iterator.hasNext()) {
                MultipartFile file = request.getFile(iterator.next());
                session.save(toImage(file));
            }
        } catch (Exception e) {
            return new ResponseEntity<UploadPictureResult>(new UploadPictureResult(),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<UploadPictureResult>(new UploadPictureResult(), HttpStatus.OK);
    } 




    public class UploadPictureResult extends WebResponse{

    private List<Image> images;

    public void setImages(List<Image> 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


0
投票
<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.0</version>
    </dependency>

我不使用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错误,帮助这可以帮助你。


0
投票

检查这个帖子。 spring mvc restcontroller return json string p / s:你应该将jack子映射配置添加到你的WebMvcConfig类

@Override protected void configureMessageConverters( List<HttpMessageConverter<?>> 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()); }


71
投票

我有同样的问题,从最新的Spring 4.1.1开始,你需要将以下jar添加到pom.xml。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.1.1</version>
</dependency>

还要确保你有以下jar:

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

406 Spring MVC Json, not acceptable according to the request "accept" headers


0
投票

这是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

我希望这对使用最新弹簧版本的人有所帮助。


0
投票

确保发送的对象(本例中为Weather)包含getter / setter


-3
投票

你可以删除@RequestMapping中的headers元素并尝试..

喜欢


@RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)

我猜spring是一个'包含检查',而不是接受标题的完全匹配。但仍然值得尝试删除header元素并检查。


15
投票

还有另一种情况会返回此状态:如果Jackson映射器无法弄清楚如何序列化bean。例如,如果您有两个相同布尔属性的访问器方法,isFoo()getFoo()

发生了什么事情,Spring的MappingJackson2HttpMessageConverter称杰克逊的StdSerializerProvider是否可以转换你的物体。在调用链的底部,StdSerializerProvider._createAndCacheUntypedSerializer抛出一个带有信息性信息的JsonMappingException。但是,这个例外被StdSerializerProvider._createAndCacheUntypedSerializer吞噬,它告诉Spring它无法转换对象。由于转换器耗尽,Spring报告说它没有给它可以使用的Accept标题,当你给它*/*时当然是假的。

这种行为有一个bug,但它被关闭为“无法重现”:被调用的方法并未声明它可以抛出,因此吞咽异常显然是一个合适的解决方案(是的,这是讽刺)。不幸的是,杰克逊没有任何记录......并且在代码库中有很多评论希望它能做到,所以我怀疑这不是唯一隐藏的问题。


14
投票

我遇到了同样的问题,我的控制器方法执行但响应是错误406.我调试AbstractMessageConverterMethodProcessor#writeWithMessageConverters并发现方法ContentNegotiationManager#resolveMediaTypes总是返回text/html不支持的MappingJacksonHttpMessageConverter。问题是org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategyorg.springframework.web.accept.HeaderContentNegotiationStrategy工作得更早,并且我的请求/get-clients.html的扩展是我的错误406问题的原因。我刚刚将请求URL更改为/get-clients


9
投票

确保在课程路径中有2个jar

如果缺少任何一个或两个,则会出现此错误。

jackson-core-asl-1.9.X.jar jackson-mapper-asl-1.9.X.jar

6
投票

终于从这里找到了答案:

Mapping restful ajax requests to spring

我引用:

@RequestBody / @ ResponseBody注释不使用普通的视图解析器,它们使用自己的HttpMessageConverters。为了使用这些注释,您应该在AnnotationMethodHandlerAdapter中配置这些转换器,如引用中所述(您可能需要MappingJacksonHttpMessageConverter)。


3
投票

检查dispatcherservlet.xml中的<mvc:annotation-driven />,如果没有添加它。并添加

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

你的pom.xml中的这些依赖项


2
投票
<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-base</artifactId>
    <version>2.6.3</version>
</dependency>

1
投票

在控制器中,响应体注释不应该在返回类型而不是方法上,如下所示:

@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完成所有操作时更容易。

© www.soinside.com 2019 - 2024. All rights reserved.