Servlet Client HTTP Requests
When a browser requests a webpage, it sends specific information to the web server, which cannot be read directly because it is transmitted as part of the HTTP request header. You can learn more about this in the HTTP Protocol tutorial.
Here are some important header information from the browser side that you frequently use in web programming:
Header | Description |
---|---|
Accept | This header specifies the MIME types that the browser or client can handle. Values like image/png or image/jpeg are the most common. |
Accept-Charset | This header specifies the character sets that the browser can use to display information, such as ISO-8859-1. |
Accept-Encoding | This header specifies the encoding types that the browser knows how to handle. Values like gzip or compress are the most common. |
Accept-Language | This header specifies the preferred language of the client, in which case the Servlet produces results in multiple languages. For example, en, en-us, ru, etc. |
Authorization | This header is used by the client to identify itself when accessing password-protected pages. |
Connection | This header indicates whether the client can handle persistent HTTP connections. Persistent connections allow the client or browser to retrieve multiple files with a single request. The value Keep-Alive means a persistent connection is used. |
Content-Length | This header is only applicable to POST requests and gives the size of the POST data in bytes. |
Cookie | This header returns cookies previously sent to the browser back to the server. |
Host | This header specifies the host and port from the original URL. |
If-Modified-Since | This header indicates that the client wants the page only if it has been modified after the specified date. If no new results are available, the server sends a 304 code indicating Not Modified. |
If-Unmodified-Since | This header is the opposite of If-Modified-Since, specifying that the operation will succeed only if the document is older than the specified date. |
Referer | This header indicates the URL of the web page that was linked to the current page. For example, if you are on webpage 1 and click a link to webpage 2, the URL of webpage 1 will be included in the Referer header when the browser requests webpage 2. |
User-Agent | This header identifies the browser or client making the request and can return different content to different types of browsers. |
Methods to Read HTTP Headers
The following methods can be used in a Servlet program to read HTTP headers. These methods are available through the HttpServletRequest object.
Number | Method & Description |
---|---|
1 | Cookie[] getCookies() <br>Returns an array containing all the Cookie objects sent by the client with this request. |
2 | Enumeration getAttributeNames() <br>Returns an enumeration containing the names of the attributes available to this request. |
3 | Enumeration getHeaderNames() <br>Returns an enumeration of all the header names in this request. |
4 | Enumeration getParameterNames() <br>Returns an enumeration of String objects containing the names of the parameters contained in this request. |
5 | HttpSession getSession() <br>Returns the current session associated with this request, or creates one if it does not exist. |
6 | HttpSession getSession(boolean create) <br>Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. |
7 | Locale getLocale() <br>Returns the preferred Locale for the client, based on the Accept-Language header. |
8 | Object getAttribute(String name) <br>Returns the value of the named attribute as an Object, or null if no attribute of the given name exists. |
9 | ServletInputStream getInputStream() <br>Retrieves the body of the request as binary data using a ServletInputStream. |
10 | String getAuthType() <br>Returns the name of the authentication scheme used to protect the Servlet, such as "BASIC" or "SSL", or null if the JSP is not protected. |
11 | String getCharacterEncoding() <br>Returns the name of the character encoding used in the body of the request. |
12 | String getContentType() <br>Returns the MIME type of the body of the request, or null if the type is not known. |
13 | String getContextPath() <br>Returns the portion of the request URI that indicates the context of the request. |
14 | String getHeader(String name) <br>Returns the value of the specified request header as a string. |
15 | String getMethod() <br>Returns the name of the HTTP method with which this request was made, such as GET, POST, or PUT. |
16 | String getParameter(String name) <br>Returns the value of a request parameter as a string, or null if the parameter does not exist. |
17 | String getPathInfo() <br>Returns any extra path information associated with the URL the client sent when the request was made. |
18 | String getProtocol() <br>Returns the name and version of the request protocol. |
19 | String getQueryString() <br>Returns the query string that is contained in the request URL after the path. |
20 | String getRemoteAddr() <br>Returns the Internet Protocol (IP) address of the client that sent the request. |
21 | String getRemoteHost() <br>Returns the fully qualified name of the client that sent the request. |
22 | String getRemoteUser() <br>Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. |
23 | String getRequestURI() <br>Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. |
24 | String getRequestedSessionId() <br>Returns the session ID specified by the client. |
25 | String getServletPath() <br>Returns the part of the URL that called the JSP for the request. |
26 | String[] getParameterValues(String name) <br>Returns an array of string objects containing all of the values the given request parameter has, or null if the parameter does not exist. |
27 | boolean isSecure() <br>Returns a boolean indicating whether the request was made using a secure channel, such as HTTPS. |
28 | int getContentLength() <br>Returns the length of the request body in bytes, or -1 if the length is not known. |
29 | int getIntHeader(String name) <br>Returns the value of the specified request header as an int. |
30 | int getServerPort() <br>Returns the port number on which this request was received. |
31 | int getParameterMap() <br>Encapsulates the parameters into a Map type. |
HTTP Header Request Example
The following example uses the getHeaderNames() method of HttpServletRequest to read the HTTP header information. This method returns an enumeration containing the header information associated with the current HTTP request.
Once we have an enumeration, we can loop through it in the standard way, using the hasMoreElements() method to determine when to stop, and the nextElement() method to get the name of each parameter.
// Import necessary Java libraries
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DisplayHeader")
// Extends HttpServlet class
public class DisplayHeader extends HttpServlet {
// Method to handle GET method request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set response content type
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String title = "HTTP Header Request Example - tutorialpro.org Example";
String docType =
"<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><meta charset=\"utf-8\"><title>" + title + "</title></head>\n"+
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<table width=\"100%\" border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
"<th>Header Name</th><th>Header Value</th>\n"+
"</tr>\n");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
// Method to handle POST method request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
The above test example is located under the TomcatTest project, with the corresponding web.xml configuration as follows:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<!-- Class name -->
<servlet-name>DisplayHeader</servlet-name>
<!-- Package location -->
<servlet-class>com.tutorialpro.test.DisplayHeader</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayHeader</servlet-name>
<!-- URL to access -->
<url-pattern>/TomcatTest/DisplayHeader</url-pattern>
</servlet-mapping>
</web-app>
Now, when calling the above Servlet, accessing http://localhost:8080/TomcatTest/DisplayHeader will produce the following result: