Reputation: 6236
When i send with Postman
a post request with JSON body (application/json
) i got this error in spring-mvc
(i am not using spring boot
)
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported
I tried all SO topics about this error but nothing works :(
I have include also the dependencies for Jackson
in my pom.xml
to map JSON objects into POJOs.
So why it keeps telling me Content type 'application/json' not supported
!
My controller
@RestController
public class FooRest {
// even with consumes=MediaType.APPLICATION_JSON_VALUE it does not work
@RequestMapping(value = "/api/foo", method = RequestMethod.POST)
public String foo(HttpServletRequest request, @RequestBody FooBean bean) {
...
}
}
My config
@Configuration
@EnableWebMvc
@ComponentScan({"controllers"})
public class AppConfig implements WebMvcConfigurer { }
My pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
...
</dependencies>
curl version
POST /MY-API HTTP/1.1
Host: 127.0.0.1:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 89859e26-813d-fb53-8726-57900f02207e
{
//JSON OBJECT
}
SOLUTION
I changed
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
To
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
And it works finally :) can someone explain me why ?
Upvotes: 2
Views: 21305
Reputation: 71
By the way, @PostMapping
is specialized version of @RequestMapping
annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST)
.
Without any change in the Spring configuration (content-negotiation
), methods annotated with @PostMapping
consumes and produces content in default media type i.e. application/json
. The use of consumes
and produces
attributes of @PostMapping
is only justified if you want to consumes and produces content in a different media type i.e. application/xml
.
So, the following code should be fine to you:
@RestController
public class FooRest {
@PostMapping("/api/foo")
public String foo(HttpServletRequest request, @RequestBody FooBean bean) {
...
}
}
And finally, you need the accepts
header in the request as application/json
Can you share us the curl
version of you request?
Upvotes: 3