我正在做一个Spring MVC控制器,我仍然遇到POST操作问题。 我已经在stackoverflow上阅读了很多解决方案,但没有解决我的问题。
我目前的成就:
POST
return = 415 UNSUPPORTED_MEDIA_TYPE
请求
1)我在我的pom.xml中添加了Jackson API:1.8.5
2)我的Spring配置文件: 我添加了所有必要的部分:
3)我的模型对象很简单:具有Id,Name和金额的帐户
@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
我出错的任何想法?
答案 0 :(得分:6)
嗯,“UNSUPPORTED_MEDIA_TYPE”应该是一个提示。您的curl
命令实际上正在发送:
Content-Type: application/x-www-form-urlencoded
只需添加明确的Content-Type
标题,您就可以了:
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
答案 1 :(得分:4)
试试这个:
curl -i -POST -H "Accept: application/json" -H "Content-type: application/json" -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account