您的位置:寻梦网首页编程乐园JAVA 天地Servlet 专辑Servlet and JSP Tutorial
Reading HTTP Request Headers

  1. An Overview of Request Headers
  2. Reading Request Headers from Servlets
  1. Example: Printing all Headers
  2. Servlet and JSP Tutorial: Top
  3. Servlet and JSP Training Courses On-site at your company or at public venues.

Note: Chapter 4 of Core Servlets and JavaServer Pages contains much more detailed and up to date information on this topic. The full text is now available online in PDF for free access.

1. An Overview of Request Headers

When an HTTP client (e.g. a browser) sends a request, it is required to supply a request line (usually GET or POST). If it wants to, it can also send a number of headers, all of which are optional except for Content-Length, which is required only for POST requests. Here are the most common headers:
  • Accept The MIME types the browser prefers.
  • Accept-Charset The character set the browser expects.
  • Accept-Encoding The types of data encodings (such as gzip) the browser knows how to decode. Servlets can explicitly check for gzip support and return gzipped HTML pages to browsers that support them, setting the Content-Encoding response header to indicate that they are gzipped. In many cases, this can reduce page download times by a factor of five or ten.
  • Accept-Language The language the browser is expecting, in case the server has versions in more than one language.
  • Authorization Authorization info, usually in response to a WWW-Authenticate header from the server.
  • Connection Use persistent connection? If a servlet gets a Keep-Alive value here, or gets a request line indicating HTTP 1.1 (where persistent connections are the default), it may be able to take advantage of persistent connections, saving significant time for Web pages that include several small pieces (images or applet classes). To do this, it needs to send a Content-Length header in the response, which is most easily accomplished by writing into a ByteArrayOutputStream, then looking up the size just before writing it out.
  • Content-Length (for POST messages, how much data is attached)
  • Cookie (one of the most important headers; see separate section in this tutorial on handling cookies)
  • From (email address of requester; only used by Web spiders and other custom clients, not by browsers)
  • Host (host and port as listed in the original URL)
  • If-Modified-Since (only return documents newer than this, otherwise send a 304 "Not Modified" response)
  • Pragma (the no-cache value indicates that the server should return a fresh document, even if it is a proxy with a local copy)
  • Referer (the URL of the page containing the link the user followed to get to current page)
  • User-Agent (type of browser, useful if servlet is returning browser-specific content)
  • UA-Pixels, UA-Color, UA-OS, UA-CPU (nonstandard headers sent by some Internet Explorer versions, indicating screen size, color depth, operating system, and cpu type used by the browser's system)
For full details on HTTP headers, see the specifications at http://www.w3.org/Protocols/.

2. Reading Request Headers from Servlets

Reading headers is very straightforward; just call the getHeader method of the HttpServletRequest, which returns a String if the header was supplied on this request, null otherwise. However, there are a couple of headers that are so commonly used that they have special access methods. The getCookies method returns the contents of the Cookie header, parsed and stored in an array of Cookie objects. See the separate section of this tutorial on cookies. The getAuthType and getRemoteUser methods break the Authorization header into its component pieces. The getDateHeader and getIntHeader methods read the specified header and then convert them to Date and int values, respectively.

Rather than looking up one particular header, you can use the getHeaderNames to get an Enumeration of all header names received on this particular request.

Finally, in addition to looking up the request headers, you can get information on the main request line itself. The getMethod method returns the main request method (normally GET or POST, but things like HEAD, PUT, and DELETE are possible). The getRequestURI method returns the URI (the part of the URL that came after the host and port, but before the form data). The getRequestProtocol returns the third part of the request line, which is generally "HTTP/1.0" or "HTTP/1.1".

3. Example: Printing all Headers

Here's a servlet that simply creates a table of all the headers it receives, along with their associated values. It also prints out the three components of the main request line (method, URI, and protocol).

3.1 ShowRequestHeaders.java

You can also download the source or try it on-line.
package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class ShowRequestHeaders extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Servlet Example: Showing Request Headers";
    out.println(ServletUtilities.headWithTitle(title) +
                "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
                "<B>Request Method: </B>" +
                request.getMethod() + "<BR>\n" +
                "<B>Request URI: </B>" +
                request.getRequestURI() + "<BR>\n" +
                "<B>Request Protocol: </B>" +
                request.getProtocol() + "<BR><BR>\n" +
                "<TABLE BORDER=1 ALIGN=CENTER>\n" +
                "<TR BGCOLOR=\"#FFAD00\">\n" +
                "<TH>Header Name<TH>Header Value");
    Enumeration headerNames = request.getHeaderNames();
    while(headerNames.hasMoreElements()) {
      String headerName = (String)headerNames.nextElement();
      out.println("<TR><TD>" + headerName);
      out.println("    <TD>" + request.getHeader(headerName));
    }
    out.println("</TABLE>\n</BODY></HTML>");
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}

3.2 ShowRequestHeaders Output

Here are the results of two typical requests, one from Netscape and one from Internet Explorer. You'll see the reason Netscape shows a Cookie header when you get to the tutorial section on cookies.

Request headers sent by Netscape
Request headers sent by Internet Explorer