How to config spring to ignore invalid Accept header?
Asked Answered
K

1

6

I'm using spring to build my web app.

In my custom WebMvcConfigurationSupport class, I setup basic ContentNegotiationConfigurer like following:

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

I cannot set ignoreAcceptHeader to true, since some of my customers rely on this header for response.

But when I try to access my API with an invalid Accept header like Accept: :*/* (note that extra colon), spring redirects to the error page /error, with the following log:

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"

Can I change this behavior? I want to ignore Accept header completely instead of jump to error page. Is that possible?

Koh answered 31/5, 2017 at 4:53 Comment(0)
K
1

Use a filter to intercept the requests with wrong header and wrap them replacing (or removing) the wrong header.

Adding an HTTP Header to the request in a servlet filter

In the example change the getHeader() method to

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); 
}
Kinesthesia answered 31/5, 2017 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.