问题
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