Servlet Filter: How to get all the headers from servletRequest?
Typecast ServletRequest
into HttpServletRequest
(only if ServletRequest request
is an instanceof
HttpServletRequest
).
Then you can use HttpServletRequest.getHeader()
and HttpServletRequest.getHeaderNames()
method.
Something like this:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
Enumeration<String> headerNames = httpRequest.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
System.out.println("Header: " + httpRequest.getHeader(headerNames.nextElement()));
}
}
//doFilter
chain.doFilter(httpRequest, response);
}
With Java 8+ you can use a stream to collect request headers:
HttpServletRequest httpRequest = (HttpServletRequest) request;
Map<String, String> headers = Collections.list(httpRequest.getHeaderNames())
.stream()
.collect(Collectors.toMap(h -> h, httpRequest::getHeader));
UPDATED
@Matthias reminded me that headers can have multiple values:
Map<String, List<String>>
Map<String, List<String>> headersMap = Collections.list(httpRequest.getHeaderNames())
.stream()
.collect(Collectors.toMap(
Function.identity(),
h -> Collections.list(httpRequest.getHeaders(h))
));
org.springframework.http.HttpHeaders
HttpHeaders httpHeaders = Collections.list(httpRequest.getHeaderNames())
.stream()
.collect(Collectors.toMap(
Function.identity(),
h -> Collections.list(httpRequest.getHeaders(h)),
(oldValue, newValue) -> newValue,
HttpHeaders::new
));
https://gist.github.com/Cepr0/fd5d9459f17da13b29126cf313328fe3
You should consider that the same HTTP header can occur multiple times with different values:
Map<String, Serializable> headers = Collections.list(request.getHeaderNames()).stream().collect(Collectors.toMap(h -> h, h -> {
ArrayList<String> headerValues = Collections.list(request.getHeaders(h));
return headerValues.size() == 1 ? headerValues.get(0) : headerValues;
}));