Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot - setting default Content-type header if it's not present in request

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 that Content-type=application/json by default.

Can I achieve this somehow using spring boot features and not using filters?

Thanks

like image 527
Andrey Yaskulsky Avatar asked Jan 11 '18 21:01

Andrey Yaskulsky


People also ask

Is Content-Type header mandatory?

No, it's not mandatory. Per the HTTP 1.1 specification: Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body.

How do I create a header for all requests in spring boot?

To set the custom header to each response, use addHeader() method of the HttpServletResponse interface. That's all about setting a header to all responses in Spring Boot.


1 Answers

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.

like image 126
N. DaSilva Avatar answered Nov 14 '22 02:11

N. DaSilva