【问题标题】:How to config spring to ignore invalid Accept header?如何配置 spring 以忽略无效的 Accept 标头?
【发布时间】:2017-10-31 17:40:05
【问题描述】:

我正在使用 spring 来构建我的网络应用程序。

在我的自定义WebMvcConfigurationSupport 类中,我设置了基本的ContentNegotiationConfigurer,如下所示:

@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
    configurer
            .favorPathExtension(false)
            .favorParameter(true)
            .parameterName("mediaType")
            .ignoreAcceptHeader(false)
            .useJaf(false)
            .defaultContentType(MediaType.APPLICATION_XML)
            .mediaType("json", MediaType.APPLICATION_JSON)
            .mediaType("xml", MediaType.APPLICATION_XML);
}

我无法将 ignoreAcceptHeader 设置为 true,因为我的一些客户依赖此标头进行响应。

但是,当我尝试使用无效的 Accept 标头(如 Accept: :*/*)访问我的 API 时(注意多余的冒号),spring 会重定向到错误页面 /error,并显示以下日志:

12:18:14.498 468443 [6061] [qtp1184831653-73] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver  
Resolving exception from handler [public MyController.myAction() throws java.io.IOException]: org.springframework.web.HttpMediaTypeNotAcceptableException: 
Could not parse accept header [: application/json,*/*]: Invalid mime type ": application/json": Invalid token character ':' in token ": application"

我可以改变这种行为吗?我想完全忽略 Accept 标头而不是跳转到错误页面。这可能吗?

【问题讨论】:

    标签: java spring http spring-mvc http-accept-header


    【解决方案1】:

    使用过滤器拦截带有错误标头的请求并将它们包装起来替换(或删除)错误的标头。

    Adding an HTTP Header to the request in a servlet filter

    在示例中将getHeader() 方法更改为

    public String getHeader(String name) {
        if ("accept".equals(name)) {
             return null; //or any valid value
        }
        String header = super.getHeader(name);
        return (header != null) ? header : super.getParameter(name); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多