Here’s a code snippet that extracts all HTTP request headers and loops through them.
The variable req represents a javax.servlet.http.HttpServletRequest reference, while header_name and header_value represent the name and value of the header. A single header name may have multiple values; if so, header_value will record the first value listed.
Enumeration<String> headers = req.getHeaderNames();
//Loop through all headers
while (headers.hasMoreElements()) {
String header_name = headers.nextElement();
String header_value = req.getHeader(header_name);
//Do something with the header name and value
}//end while loop going through headers.
Remember that HTTP header names are case-insensitive. If you’re doing any comparisons, you may want to turn the name into a lowercase form:
String header_name_lowercase = header_name.toLowerCase();
Don’t forget to import the Enumeration class:
import java.util.Enumeration;