我正在做一个 Spring MVC Controller ,但我仍然遇到 POST 操作的问题。 我在 stackoverflow 上阅读了很多解决方案,但都没有解决我的问题。
我目前的成就:
- 我发送了一个带有 Id 的 GET 请求,并返回了一个成功转换为 JSON 的对象。
- 我未能发送带有 JSON 正文的
POST
请求,return = 415 UNSUPPORTED_MEDIA_TYPE
1) 我在 pom.xml 中添加了 Jackson API : 1.8.5
2)我的Spring配置文件: 我添加了所有必要的部分:
- View 解析器
- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
- MappingJacksonHttpMessageConverter
- mvc:注解驱动
- 扫描我的 Controller
3) 我的模型对象很简单:一个带有 ID、名称和金额的帐户
@Document
public class Account implements Serializable {
private static final long serialVersionUID = 9058933587701674803L;
@Id
private String id;
private String name;
private Double amount=0.0;
// and all get and set methods
4) 最后是我的简化 Controller 类:
@Controller
public class AdminController {
@RequestMapping(value="/account", method=RequestMethod.POST,
headers = {"content-type=application/json"})
@ResponseStatus( HttpStatus.CREATED )
public void addAccount(@RequestBody Account account){
log.debug("account from json request " + account);
}
@RequestMapping(value="/account/{accountId}", method=RequestMethod.GET)
@ResponseBody
public Account getAccount(@PathVariable("accountId") long id){
log.debug("account from json request " + id);
return new Account();
}
}
5) 在客户端,我刚刚执行了 curl 命令:
成功的 GET
命令:
curl -i -GET -H 'Accept: application/json' http://myhost:8080/compta/account/1
失败的 POST
命令:
curl -i -POST -H 'Accept: application/json' -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account
有什么地方出错了吗?
最佳答案
嗯,“UNSUPPORTED_MEDIA_TYPE”应该是一个提示。您的 curl
命令实际上正在发送:
Content-Type: application/x-www-form-urlencoded
只需添加明确的 Content-Type
header 即可:
curl -v -i -POST -H 'Accept: application/json' -H 'Content-Type: application/json' -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account
关于rest - Spring MVC 3.1 REST服务post方法返回415,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14222681/