Reading Request Headers from Servlets
by, 11-28-2011 at 07:31 PM (1154 Views)
It is relatively easy to read headers. All you need to do is call the getHeader method of HttpServletRequest. If the specified header exists, the servlet returns a String, if not the servlet will return null. Unlike parameter names, header names are not case sensitive. Although getHeader is a general-purpose way to read incoming headers, there are a couple of headers that are so commonly used that they have special access methods in HttpServletRequest. They are listed below.
- getCookies - The getCookies method returns the contents of the Cookie header, parsed and stored in an array of Cookie objects. This method is discussed more in Chapter 8 (Handling Cookies).
- getAuthTypeandgetRemoteUser - The getAuthType and getRemoteUser methods break the Authorization header into its component pieces. Use of the Authorization header is illustrated in Section 4.5 (Restricting Access to Web Pages).
- getContentLength - The getContentLength method returns the value of the Content-Length header (as an int).
- getContentType - The getContentType method returns the value of the Content-Type header (as a String).
- getDateHeaderandgetIntHeader - The getDateHeader and getIntHeader methods read the specified header and then convert them to Date and int values, respectively.
- getHeaderNames - With the getHeaderNames method you are returned an Enumeration of all header names received on this particular request.
- getHeaders - In most cases, each header name appears only once in the request. Sometimes a header can appear multiple times, with each occurrence listing a separate value. Accept-Language is one such example. If a header name is repeated in the request, version 2.1 servlets cannot access the later values without reading the raw input stream, since getHeader returns the value of the first occurrence of the header only. In version 2.2, however, getHeaders returns an Enumeration of the values of all occurrences of the header.
Below are the information on request headers that you can get information on the main request line itself, also by means of methods in HttpServletRequest.
- getMethod - The getMethod method returns the main request method (normally GET or POST, but things like HEAD, PUT, and DELETE are possible).
- getRequestURI - The getRequestURI method returns the part of the URL that comes after the host and port but before the form data. For example, for a URL of http://randomhost.com/servlet/search.BookSearch, getRequestURI would return /servlet/search.BookSearch.
- getProtocol - Lastly, the getProtocol method returns the third part of the request line, which is generally HTTP/1.0 or HTTP/1.1. Servlets should usually check getProtocol before specifying response headers (Chapter 7) that are specific to HTTP 1.1.