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.

Share:
10,849

Related videos on Youtube

Andrey Yaskulsky
Author by

Andrey Yaskulsky

Updated on June 04, 2022

Comments

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

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

    Thanks

    • ESala
      ESala over 6 years
      can you add a small code example of how you are using the header?
    • radistao
      radistao over 6 years
      are talking about request or response content type? Did you try @RequestMapping(consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE) ?
    • best wishes
      best wishes over 6 years
      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.
    • Sachin Verma
      Sachin Verma almost 5 years
      he is asking if we can modify request to add a Content-Type header if its not sent by client.
    • KevinO
      KevinO about 4 years
  • eis
    eis about 4 years
    this is incorrect. This is equivalent of setting default "Accept" header, not of default "Content-Type" header, so will only impact responses, not requests.