In the spring boot (2.2.3 RELEASE) application, the 'Content-Length' header is not added explicitly but, present in every response.
There is now a requirement to add the 'Transfer-Encoding' header to the response. When it is added and the API is tested via Postman, it shows an error.
Console log:
Error: Parse Error: Content-Length can't be present with Transfer-Encoding
Which was found to be in sync with IETF HTTP 1.1 RFC7230 document.
Since the 'Content-Length' header is not required in the response API, it's filtered out using @WebFilter annotation.
@Order annotation is added with MAX Integer value to ensure that this filter is executed at the end.
@WebFilter(urlPatterns = "/*", asyncSupported = true)
@Order(Integer.MAX_VALUE)
public class ContentLengthHeaderFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(ContentLengthHeaderFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("filter init called !!!");
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
LOGGER.info("doFilter called ...............@@@");
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
@Override
public void addHeader(String name, String value) {
if (!HttpHeaders.CONTENT_LENGTH.equals(name)) {
LOGGER.info("adding header :" + name);
super.addHeader(name, value);
}
}
@Override
public void setHeader(String name, String value) {
if (!HttpHeaders.CONTENT_LENGTH.equals(name)) {
LOGGER.info("setting header :" + name);
super.setHeader(name, value);
}
}
});
}
@Override
public void destroy() {
LOGGER.info("filter destroy called !!!");
Filter.super.destroy();
}
}
The logs shows that headers other than 'Content-Length' are added.
13.10.2022 11:25:34.947+0530 INFO [o.s.web.servlet.DispatcherServlet] [http-nio-8080-exec-1] Completed initialization in 8 ms
13.10.2022 11:25:34.959+0530 INFO [a.b.c.d.ContentLengthHeaderFilter] [http-nio-8080-exec-1] doFilter called ...............@@@
13.10.2022 11:25:36.597+0530 INFO [a.b.c.d.ContentLengthHeaderFilter] [http-nio-8080-exec-3] adding header :Location
13.10.2022 11:25:36.597+0530 INFO [a.b.c.d.ContentLengthHeaderFilter] [http-nio-8080-exec-3] adding header :X-CustomHeader
13.10.2022 11:25:36.597+0530 INFO [a.b.c.d.ContentLengthHeaderFilter] [http-nio-8080-exec-3] adding header :Transfer-Encoding
Still the API call results in 'Content-Length' header getting added to the response which causes the error mentioned above. Am I messing any thing or is there any other way to remove 'Content-Length' header?