Spring MVC 3.1 REST services post method return 415

若如初见. 提交于 2019-12-02 06:07:39

问题


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.

My achievement at the moment :

  • I sent a GET request with an Id and return an Object converted to JSON successfully.
  • I failed to send a POST request with a JSON body, return = 415 UNSUPPORTED_MEDIA_TYPE

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

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

  • viewResolver
  • org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
  • MappingJacksonHttpMessageConverter
  • mvc:annotation-driven
  • scan my controllers

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) 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) 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

The POST command which failed:

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?


回答1:


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

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

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



回答2:


Try this :

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


来源:https://stackoverflow.com/questions/14222681/spring-mvc-3-1-rest-services-post-method-return-415

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!