2017-05-31 858 views
2

我使用spring来构建我的web应用程序。如何配置spring忽略无效Accept头?

在我的自定义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); 
} 

我无法设置ignoreAcceptHeadertrue,因为我的一些客户的依赖这个头的响应。

但是当我尝试用无效Accept头像Accept: :*/*访问我的API(注意额外的冒号),弹簧重定向到/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标题,而不是跳转到错误页面。那可能吗?

回答

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