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 :
POST request with a JSON body, return = 415 UNSUPPORTED_MEDIA_TYPE1) 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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With