- Java EE Tutorials
- Servlets Tutorials
- Servlets Interview Questions
Request Header
Request header is used to pass additional information about the request or itself to the server. Request header can be used by client to pass useful information. getHeaderNames() and getHeader() methods of javax.servlet.http.HttpServletRequest interface can be used to get the header information. Following important request header information which comes from browser side can be frequently used while programming:
- Accept: This specifies the certain media types that are acceptable in the response.
- Accept-Charset: This indicates the character sets that are acceptable in the response.
- Accept-Encoding: This restricts the content-coding values that are acceptable in the response
- Accept-Language: This restricts the set of language that are preferred in the response.
- Authorization : This type indicates that user agent is attempting to authenticate itself with a server.
- From: This type contains internet email address for the user who controls the requesting user agent.
- Host: This type indicates internet host and port number of the resource being requested.
- If-Modified-Since: This type makes GET method condition. Do not return the requested information if it is not modified since the specified date.
- Range: This type request one or more sub-range of the entity, instead of the entire entity.
- Referer: This type enables client to specify, for the servers benefit, the address(URL) of the resources from which the Request-URL was obtained.
- User-Agent: This type contains information about the user agent originating the request.
Request Header Example
Following example displays the HTTP header information. Here we have used method getHeaderNames() to get the information.
package javabeat.net.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestHeaderDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Headers<hr/>"); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); out.print("Header Name: <em>" + headerName); String headerValue = request.getHeader(headerName); out.print("</em>, Header Value: <em>" + headerValue); out.println("</em><br/>"); } } }
Execute the above program in Eclipse. Right mouse click on the class RequestHeaderDemoOutput, select Run > Run As and an output as below would be seen:
Previous Tutorial : How To Refresh Servlet || Next Tutorial : Session Tracking Using Servlet