java - 使用 Spring 3 和 Jackson 1.9 的简单请求中出现错误 406

标签 java json spring jackson

我使用 Jackson 1.9 和 Spring 3 创建了一个简单的测试用例。我的目标是测试使用它们生成 JSON 结果有多么容易。我的问题是我收到错误 406

到目前为止,似乎只需要配置Spring,代码也非常简单。我的 Spring 配置文件只是:

<context:component-scan base-package="com.goldengecko" />
<context:annotation-config/>
<mvc:annotation-driven />

还有我的 Controller :

@Controller
public class TestsController
{
    @RequestMapping(value = "/tests", method=RequestMethod.GET)
    public @ResponseBody Item getBooks() {
        return new Item();
    }
}

Item 类只是:

public class Item {
    private String name;

    public Item() {
        name = "Test name";
    }

    private String getName() {
        return name;
    }

    private void setName( String name ) {
        this.name = name;
    }   
}

我确保添加了 jackson-core-asl.jar 和 jackson-mapper-asl.jar。

从我读到的所有内容来看,就是这样:您似乎不需要担心在请求中设置接受的内容,只需打开普通的 Chrome 浏览器并请求该服务即可。

这就是我得到 406 的地方。

我创建了一个简单的 jQuery getJSON 调用,具有相同的结果。

你知道可能出什么问题吗?到目前为止,几乎没有什么会失败的:代码似乎是正确的方法,而且 Spring 所需的 Jackson 文件也在那里。

最佳答案

根据http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html第10.4.7节:

The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

Unless it was a HEAD request, the response SHOULD include an entity containing a list of available entity characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. Depending upon the format and the capabilities of the user agent, selection of the most appropriate choice MAY be performed automatically. However, this specification does not define any standard for such automatic selection.

Note: HTTP/1.1 servers are allowed to return responses which are not acceptable according to the accept headers sent in the request. In some cases, this may even be preferable to sending a 406 response. User agents are encouraged to inspect the headers of an incoming response to determine if it is acceptable.

如果响应 Not Acceptable ,用户代理应该暂时停止接收更多数据并询问用户以决定进一步的操作。

所以听起来您可能确实需要在接收端设置可接受的内容类型。

关于java - 使用 Spring 3 和 Jackson 1.9 的简单请求中出现错误 406,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8048406/

相关文章:

json - 如何解析 JSON 文件?

java - Maven 与较旧的 Spring Boot 版本的依赖关系

java - Hibernate:通过从某个位置读取 hbm 映射文件来创建动态表

java - 如何在 Spring Requestmapping 中将日期作为对象参数发布

java - 如何在 Eclipse 中找到正确的重写方法

java - 在 Java 中连接 mp3 文件

php - 我们如何在 JQuery Append 函数中运行 If else 语句?

javascript - 如何在 Knockout js 中提供分页

java - 失败时显示查询绑定(bind)的参数

java - 如何比较两个数组并获取最低的一个并添加零