How to create a POST request in REST to accept a J

2019-05-21 11:52发布

问题:

I am trying to learn RESTful web services. And am creating a simple set of web services. Got stuck when I started working on POST.

I want to pass JSON input to a POST method. This is what I did in the code:

@RequestMapping(value = "/create", method = RequestMethod.POST, consumes="application/x-www-form-urlencoded", produces="text/plain")
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody String createChangeRequest(MyCls mycls) {
    return "YAHOOOO!!"; 
}

I included Jackson in my POM.xml.

 <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-lgpl</artifactId>
    <version>1.9.13</version>
</dependency>   

MyCls is a simple class with a few getters and setters.

I am calling the above POST service from chrome's simple REST client.

URL: http://localhost:8080/MYWS/cls/create
Data: {<valid-json which corresponds to each variable in the MyCls pojo}

I see the below response:

415 Unsupported Media Type
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

I tried adding header as "application/json" in the POST request in the REST client - but that did not help.

Can someone let me know what I am missing here? How can I automatically map my input JSON to the MyCls pojo? Am I missing any configuration here?

Edit: MyCls.java

public class MyCls{
   private String name;
   private String email;
   private String address;
       public String getName() {
    return name;
   }
   public void setName(String name) {
    name= name;
   }
       ---similar getter and setter for email, address--
}

json from chrome Simple REST Client:

{"name":"abc", "email":"de@test","address":"my address"}

Edit: Changed my controller method to the following, but still see the same error:

@RequestMapping(value = "/create", method = RequestMethod.POST, consumes="application/json", produces="text/plain")
@ResponseStatus(HttpStatus.CREATED)
 public @ResponseBody String createChangeRequest(@RequestBody MyCls mycls) {
  return "YAHOOOO!!"; 
 }

回答1:

Assuming your client is sending application/json as its content type, then a handler mapped to

consumes="application/x-www-form-urlencoded"

will not be able to handle it. The actual Content-type doesn't match the expected.

If you are expecting application/json, you should instead have

consumes="application/json"

Also, declaring

public @ResponseBody String createChangeRequest(MyCls mycls) {

is (in default environment) equivalent to

public @ResponseBody String createChangeRequest(@ModelAttribute MyCls mycls) {

This means the MyCls object is created from request parameters, not from JSON body. Instead, you should have

public @ResponseBody String createChangeRequest(@RequestBody MyCls mycls) {

so that Spring deserializes your JSON to an object of type MyCls.