springframework get all request headers
Asked Answered
A

2

31

I know that spring3 has @RequestHeader to get a single request header in a controller. I'm wondering if there is an easy way to get ALL the request headers? I'm hoping for something like this:

@RequestMapping(value="/some/url",RequestMethod.GET)
public void endpoint(RequestParams params, BindingResult result, @RequestHeader MultiValueMap<String,String> headers, HttpServletRequest request, ModelMap model) {

}

Currently I'm doing something like this:

MultiValueMap<String,String> headers = new HttpHeaders();
for (Enumeration names = request.getHeaderNames(); names.hasMoreElements();) {
    String name = (String)names.nextElement();
    for (Enumeration values = request.getHeaders(name); values.hasMoreElements();) {
        String value = (String)values.nextElement();
        headers.add(name,value);
    }
}
Amylopectin answered 28/7, 2011 at 17:54 Comment(0)
T
51

From the Javadocs:

@RequestHeader can be used on a Map, MultiValueMap, or HttpHeaders method parameter to gain access to all request headers.

More info is available online here and there.

Transpose answered 28/7, 2011 at 18:28 Comment(0)
F
0

if you don't want to read doc:

mappingMethodName(@RequestHeader Map<String, String> headers) {
    headers.forEach((key, value) -> {
        System.out.printf("Header '%s' = %s%n", key, value);
    });
}
Fayina answered 16/6, 2022 at 17:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.