Spring boot - 如果请求中不存在,则设置默认的 Content-type 标头 [英] Spring boot - setting default Content-type header if it's not present in request

查看:51
本文介绍了Spring boot - 如果请求中不存在,则设置默认的 Content-type 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

谢谢

推荐答案

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

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 );
    }
}

在 1.x 下,您可以使用 WebMvcConfigurerAdapter 做同样的事情,现在已弃用.

Under 1.x, you could do the same thing with WebMvcConfigurerAdapter, which is now deprecated.

这将影响请求和响应主体,因此如果您没有明确设置生产"参数,并且您想要除 application/json 之外的其他内容,它将被强制转换为 application/json.

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.

这篇关于Spring boot - 如果请求中不存在,则设置默认的 Content-type 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆