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!!";
}
Assuming your client is sending
application/json
as its content type, then a handler mapped towill not be able to handle it. The actual
Content-type
doesn't match the expected.If you are expecting
application/json
, you should instead haveAlso, declaring
is (in default environment) equivalent to
This means the
MyCls
object is created from request parameters, not from JSON body. Instead, you should haveso that Spring deserializes your JSON to an object of type
MyCls
.