Spring boot - 如果请求中不存在,则设置默认的 Content-type 标头

And*_*sky 6 spring spring-mvc spring-boot

我遇到了以下问题:假设我有时会收到未Content-type设置标头的POST 请求。在这种情况下,我想Content-type=application/json默认情况下假设。

我可以使用 Spring Boot 功能而不使用过滤器以某种方式实现这一点吗?

谢谢

N. *_*lva 7

从 Spring Boot 2.x 开始,您需要创建一个扩展 WebMvcConfigurer 接口的类,例如:

@Configuration
class WebMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void configureContentNegotiation( ContentNegotiationConfigurer configurer )
    {
        configurer.defaultContentType( MediaType.APPLICATION_JSON );
    }
}
Run Code Online (Sandbox Code Playgroud)

在 1.x 下,您可以使用 WebMvcConfigurerAdapter 执行相同的操作,但现已弃用。

这将影响请求和响应主体,因此,如果您没有显式设置“产生”参数,并且您想要 application/json 之外的其他内容,那么它将被强制为 application/json。

  • 这是不正确的。这相当于设置默认的“Accept”标头,而不是默认的“Content-Type”标头,因此只会影响响应,而不影响请求。 (6认同)