我正在尝试学习 RESTful Web 服务。并正在创建一组简单的网络服务。当我开始处理 POST 时遇到了困难。
我想将 JSON 输入传递给 POST 方法。这就是我在代码中所做的:
@RequestMapping(value = "/create", method = RequestMethod.POST, consumes="application/x-www-form-urlencoded", produces="text/plain")
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody String createChangeRequest(MyCls mycls) {
return "YAHOOOO!!";
}
我将 Jackson 包含在我的 POM.xml 中。
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
MyCls 是一个简单的类,带有一些 getter 和 setter。
我从 Chrome 的简单 REST 客户端调用上述 POST 服务。
URL: http://localhost:8080/MYWS/cls/create
Data: {<valid-json which corresponds to each variable in the MyCls pojo}
我看到以下回复:
415 Unsupported Media Type
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
我尝试在 REST 客户端的 POST 请求中添加 header 作为“application/json” - 但这没有帮助。
有人可以让我知道我在这里缺少什么吗?如何自动将输入 JSON 映射到 MyCls pojo?我这里缺少任何配置吗?
编辑: MyCls.java
public class MyCls{
private String name;
private String email;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
name= name;
}
---similar getter and setter for email, address--
}
来自 chrome 简单 REST 客户端的 json:
{"name":"abc", "email":"de@test","address":"my address"}
编辑: 将我的 Controller 方法更改为以下,但仍然看到相同的错误:
@RequestMapping(value = "/create", method = RequestMethod.POST, consumes="application/json", produces="text/plain")
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody String createChangeRequest(@RequestBody MyCls mycls) {
return "YAHOOOO!!";
}
最佳答案
假设您的客户端发送 application/json
作为其内容类型,则处理程序映射到
consumes="application/x-www-form-urlencoded"
将无法处理它。实际的 Content-type
与预期不匹配。
如果您需要 application/json
,则应该改为
consumes="application/json"
另外,声明
public @ResponseBody String createChangeRequest(MyCls mycls) {
(在默认环境中)相当于
public @ResponseBody String createChangeRequest(@ModelAttribute MyCls mycls) {
这意味着 MyCls
对象是从请求参数创建的,而不是从 JSON 正文创建的。相反,你应该有
public @ResponseBody String createChangeRequest(@RequestBody MyCls mycls) {
以便 Spring 将您的 JSON 反序列化为 MyCls
类型的对象。
关于json - 如何在 REST 中创建 POST 请求以接受 JSON 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21417115/