Retrieving HTTP request headers

Retrieving HTTP request headers


Posted in : Servlet Posted on : November 9, 2010 at 4:59 PM Comments : [ 0 ]

This section contains the details about the Retrieving HTTP request headers.

Retrieving HTTP request headers

HttpServletRequest Interface provide us support for retrieving request parameters and accessing HTTP request header information.

HTTP requests have number of associated headers. These headers provide extra information about the client, such as the name and the version of browser sending the request. Some of the important HTTP request headers are :

  • Accept:  Specifies the MIME type that the client prefers to accept.

  • Accept-Language:  Specifies the language in which the client prefers to receive the request.

  • User-Agent:  Specifies the name and version of the browser sending the request.

Example

package devmanuals;

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

public class GetRequestHeader extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
/* Obtain all header names as an Enumeration */
Enumeration hnames = req.getHeaderNames();
out.println("<H3>The request headers are:</H3>");
/* Check for more elements in the Enumeration */
while (hnames.hasMoreElements()) {
/* Obtain the header name */
String hname = (String) hnames.nextElement();
/*
* Obtain all header values as an Enumeration corresponding to the
* header name passed as method parameter
*/
Enumeration hvalues = req.getHeaders(hname);
out.println("<BR>");
if (hvalues != null) {
/*
* Check for more elements in the Enumeration
*/
while (hvalues.hasMoreElements()) {
/* Obtain the header value */
String hvalue = (String) hvalues.nextElement();
/*
* Send the header name and value as response
*/
out.println(hname + ": " + hvalue);
}
}
}
}
}

Output :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics