Spring MVC 3.1 REST服务发布方法返回415 [英] Spring MVC 3.1 REST services post method return 415

查看:172
本文介绍了Spring MVC 3.1 REST服务发布方法返回415的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个Spring MVC控制器,而POST操作仍然有问题. 我已经阅读了许多关于stackoverflow的解决方案,但并没有解决我的问题.

I'm doing a Spring MVC controller and I still get problem with POST operation. I've read many solutions on stackoverflow without to fix my problem.

我目前的成就:

  • 我发送了一个带有ID的GET请求,并成功返回了一个转换为JSON的对象.
  • 我无法发送带有JSON正文return = 415 UNSUPPORTED_MEDIA_TYPE
  • POST请求

1)我将Jackson的API添加到了pom.xml:1.8.5

1) I added to my pom.xml the Jackson API : 1.8.5

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

2) My Spring configuration file: I added all necessary parts :

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

3)我的模型对象很简单:具有ID,名称和金额的帐户

3) My model object is simple : an Account with Id, Name and an amount

@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类:

4) and finally my simplified Controller class :

@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命令成功:

5) On client side I've just executed curl commands : The successfully GET command :

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

有什么想法我要去哪里吗?

Any ideas where I'm going wrong?

推荐答案

"UNSUPPORTED_MEDIA_TYPE"应该是一个提示.您的curl命令实际上正在发送:

Well, "UNSUPPORTED_MEDIA_TYPE" should be a hint. Your curl command is actually sending:

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

只需添加显式的Content-Type标头,您就可以开始了:

Simply add explicit Content-Type header and you're good to go:

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

这篇关于Spring MVC 3.1 REST服务发布方法返回415的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆