2013-01-08 132 views
2

我正在做一个Spring MVC控制器,我仍然遇到POST操作的问题。 我已经阅读了很多解决方案在stackoverflow没有解决我的问题。Spring MVC 3.1 REST服务post方法返回415

我成就的时刻:

  • 我发送GET请求一个ID,并返回转化为成功的JSON对象。
  • 我无法发送POST请求,以此JSON身体,return = 415 UNSUPPORTED_MEDIA_TYPE

1)我加入到我的pom.xml杰克逊API:1.8.5

2)我的Spring配置文件: 我添加了所有必需的部件:

  • 的ViewResolver
  • org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
  • MappingJacksonHttpMessageConverter
  • MVC:注解驱动
  • 扫描我控制器

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 
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)在客户端,我只是执行命令卷曲: 的成功GET命令:

curl -i -POST -H 'Accept: application/json' -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account 

任何想法,我要去哪里错了:

curl -i -GET -H 'Accept: application/json' http://myhost:8080/compta/account/1 

其失败的POST命令?

回答

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 
+0

THX:

Content-Type: application/x-www-form-urlencoded 

只需添加明确Content-Type头,你是好去。选项-X不会用我的curl命令返回结果。和Contet类型返回另一个错误的HTTP状态:400 – user1842947

6

嗯, “UNSUPPORTED_MEDIA_TYPE” 应该是一个暗示。你curl命令实际发送:你的回答

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 
+0

感谢您的回答,我现在得到另一个错误的HTTP状态400 – user1842947

+1

@ user1842947:这意味着您发送的是不正确的JSON(*错误的请求*),Spring MVC无法解析。请提供更多关于您的问题的详细信息,或者(更好)将此问题标记为已回答并打开另一个问题。 –

+0

好吧,thx,我尝试添加我的控制器类在我的问题的更多细节,但我得到有关缩进代码(4空格)堆栈溢出错误消息我尝试修复它,我会发布它 – user1842947