7

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

Andrey Yaskulsky
  • 2,458
  • 9
  • 39
  • 81
  • 1
    can you add a small code example of how you are using the header? – ESala Jan 11 '18 at 21:39
  • are talking about request or response content type? Did you try `@RequestMapping(consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)` ? – radistao Jan 11 '18 at 21:50
  • 1
    the 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. – best wishes Jan 12 '18 at 03:11
  • 1
    he is asking if we can modify request to add a Content-Type header if its not sent by client. – Sachin Verma Jul 08 '19 at 12:06
  • Does this answer your question? [How to set the default content type in Spring MVC in no Accept header is provided?](https://stackoverflow.com/questions/18189245/how-to-set-the-default-content-type-in-spring-mvc-in-no-accept-header-is-provide) – KevinO Apr 08 '20 at 22:16

1 Answers1

7

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.

N. DaSilva
  • 174
  • 3
  • 4
  • 6
    this is incorrect. This is equivalent of setting default "Accept" header, not of default "Content-Type" header, so will only impact responses, not requests. – eis Feb 06 '20 at 15:27