Spring MVC 3.1 REST服务post方法返回415

use*_*947 2 rest post spring-mvc http-status-code-415

我正在做一个Spring MVC控制器,我仍然遇到POST操作问题.我已经在stackoverflow上阅读了许多解决方案而无法解决我的问题.

我目前的成就:

  • 我发送了带有Id的GET请求,并成功返回转换为JSON的Object.
  • 我没有POST用JSON正文发送请求,return = 415 UNSUPPORTED_MEDIA_TYPE

1)我在我的pom.xml中添加了Jackson API:1.8.5

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

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

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 
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

5)在客户端,我刚刚执行了curl命令:成功GET命令:

curl -i -GET -H 'Accept: application/json'  http://myhost:8080/compta/account/1
Run Code Online (Sandbox Code Playgroud)

POST失败的命令:

curl -i -POST -H 'Accept: application/json' -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account
Run Code Online (Sandbox Code Playgroud)

我出错的任何想法?

Tom*_*icz 6

那么,"UNSUPPORTED_MEDIA_TYPE"应该是一个暗示.您的curl命令实际上是发送:

Content-Type: application/x-www-form-urlencoded
Run Code Online (Sandbox Code Playgroud)

只需添加显式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
Run Code Online (Sandbox Code Playgroud)