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

标签 rest post spring-mvc http-status-code-415

我正在做一个 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/

相关文章:

java - 在 ResourceSupports 中包含链接实体的片段

python - 使用 Python 请求库向 DVWA 发布请求时缺少 CSRF token

php - PHP 中的 HTTP POST 请求

java - 如何使用 Spring <form :input> 显示列表

java - 在 Spring 应用程序中使用 SecurityContextHolder 的安全实用程序

REST API 和消息传递

wcf - 将 WCF REST 4.0 部署到 XP IIS 5?

java - 将 'form-data' 设置为 Jersey 客户端发布请求

java - 在一行中获取整个 POST 响应

java - Spring MVC url 模式语法