Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to config spring to ignore invalid Accept header?

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?

like image 844
Void Main Avatar asked Nov 08 '22 21:11

Void Main


1 Answers

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); 
}
like image 159
StanislavL Avatar answered Nov 14 '22 21:11

StanislavL