我使用 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 ,用户代理应该暂时停止接收更多数据并询问用户以决定进一步的操作。
block 引用>所以听起来您可能确实需要在接收端设置可接受的内容类型。
关于java - 使用 Spring 3 和 Jackson 1.9 的简单请求中出现错误 406,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8048406/