Reputation: 67
I have the following code:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpHeaders httpHeaders = Collections.list(httpServletRequest.getHeaderNames())
.stream()
.collect(Collectors.toMap(
Function.identity(),
h -> Collections.list(httpServletRequest.getHeaders(h)),
(oldValue, newValue) -> newValue,
HttpHeaders::new
));
System.out.println(httpHeaders);
chain.doFilter(request, response);
}
It works just fine, but I would only need to get a few specific data, like accept-encoding and accept language. Is it possible to do that somehow?
Upvotes: 0
Views: 244
Reputation: 2303
One possible solution for this
List<String> headerNames = Arrays.asList("Accept-Encoding", "Content-Type");
Map<String, String> headers = headerNames.stream()
.collect(Collectors.toMap(Function.identity(), header -> httpServletRequest.getHeader(header)));
Or if you want to get HttpHeaders as a result
List<String> headers = Arrays.asList("Accept-Encoding", "Content-Type");
HttpHeaders httpHeaders = new HttpHeaders();
headers.forEach(header -> {
request.getHeaders(header)
.asIterator()
.forEachRemaining(value -> httpHeaders.add(header, value));
});
Upvotes: 1