Issue
I'm getting an error (Handler execution resulted in exception: Content type 'application/json' not supported) when trying to receive a post request using Spring MVC.
My Json, just for testing, is pretty simple:
{ "test": "abc123" }
My pojo class:
public class Request {
String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
And my controller:
@RequestMapping(value = "/testing", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
private void testing(@RequestBody Request body, @RequestHeader HttpHeaders headers, HttpServletRequest httpRequest) {
System.out.println(body.getTest());
}
In my pom.xml, I added:
<dependencies>
...
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.4.3</version>
</dependency>
</dependencies>
I think that something is wrong in json deserialization, but I cannot find it.
Any help is welcome. Thanks.
Solution
Here is my working example:
@SpringBootApplication
@Controller
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@RequestMapping(value = "/testing", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
private void testing(@RequestBody Request body, @RequestHeader HttpHeaders headers, HttpServletRequest httpRequest) {
System.out.println(body.getTest());
}
}
This project has only 1 dependency:
org.springframework.boot:spring-boot-starter-web
When I call the url like this:
curl -XPOST -v -d '{ "test": "abc123" }' -H "Content-type: application/json" http://localhost:8080/testing
I see the correct abc123
in the logs. If I remove Content-type
header I get the exception
org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/x-www-form-urlencoded' not supported
Answered By - Nikem