Spring boot - setting default Content-type header if it's not present in request
10,849
As of Spring Boot 2.x, you need to create a class that extends the WebMvcConfigurer interface, e.g.:
@Configuration
class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void configureContentNegotiation( ContentNegotiationConfigurer configurer )
{
configurer.defaultContentType( MediaType.APPLICATION_JSON );
}
}
Under 1.x, you could do the same thing with WebMvcConfigurerAdapter, which is now deprecated.
This will affect both request and response bodies, so if you do not have a "produces" parameter explicitly set, and you wanted something other than application/json, it's going to get coerced to application/json.
Related videos on Youtube
Author by
Andrey Yaskulsky
Updated on June 04, 2022Comments
-
Andrey Yaskulsky almost 2 years
I'm having the following problem: suppose I sometimes receive POST requests with no
Content-type
header set. In this case I want to assume thatContent-type=application/json
by default.Can I achieve this somehow using spring boot features and not using filters?
Thanks
-
ESala over 6 yearscan you add a small code example of how you are using the header?
-
radistao over 6 yearsare talking about request or response content type? Did you try
@RequestMapping(consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
? -
best wishes over 6 yearsthe answer suggested by @radistao will enforce the api to take json only, if you send a xml, api will respond saying this content-type is not supported. So If xml is also acceptable then include xml in the consumes list.
-
Sachin Verma almost 5 yearshe is asking if we can modify request to add a Content-Type header if its not sent by client.
-
KevinO about 4 yearsDoes this answer your question? How to set the default content type in Spring MVC in no Accept header is provided?
-
-
eis about 4 yearsthis is incorrect. This is equivalent of setting default "Accept" header, not of default "Content-Type" header, so will only impact responses, not requests.