user1842947
user1842947

Reputation: 1126

Spring MVC 3.1 REST services post method return 415

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 :

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

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

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?

Upvotes: 2

Views: 4363

Answers (2)

Jean-Philippe Bond
Jean-Philippe Bond

Reputation: 10649

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

Upvotes: 4

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

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

Upvotes: 6

Related Questions