YouTip LogoYouTip

Servlet Client Request

Servlet Client HTTP Requests

Servlet Client HTTP Requests

When a browser requests a web page, it sends specific information to the web server. This information cannot be read directly because it is transmitted as part of the HTTP request headers. You can learn more about the HTTP protocol.

Here are the important headers from the browser side that you will frequently use in web programming:

Header Description
Accept This header specifies the MIME types that the browser or other clients can handle. The values image/png or image/jpeg are the two most common possible values.
Accept-Charset This header specifies the character set that the browser can use to display information. For example, ISO-8859-1.
Accept-Encoding This header specifies the encoding types that the browser knows how to handle. The values gzip or compress are the two most common possible values.
Accept-Language This header specifies the client's preferred language, in which case the Servlet will produce 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 web pages.
Connection This header indicates whether the client can handle persistent HTTP connections. Persistent connections allow the client or other browsers to retrieve multiple files through a single request. The value Keep-Alive means a persistent connection is used.
Content-Length This header applies only 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 there are no new results available, the server sends a 304 code, indicating a Not Modified header.
If-Unmodified-Since This header is the opposite of If-Modified-Since; it specifies that the operation will succeed only if the document is earlier than the specified date.
Referer This header indicates the URL of the web page that referred to the requested page. For example, if you are on Page 1 and click a link to Page 2, when the browser requests Page 2, the URL of Page 1 will be included in the Referer header.
User-Agent This header identifies the browser or other client making the request and can return different content to different types of browsers.

Methods for Reading HTTP Headers

The following methods can be used in a Servlet program to read HTTP headers. These methods are available through the HttpServletRequest object.

No. Method & Description
1 Cookie[] getCookies()
Returns an array containing all Cookie objects sent by the client with this request.
2 Enumeration getAttributeNames()
Returns an enumeration containing the names of the attributes available to this request.
3 Enumeration getHeaderNames()
Returns an enumeration containing all the header names included in this request.
4 Enumeration getParameterNames()
Returns an enumeration of String objects containing the names of the parameters contained in this request.
5 HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
6 HttpSession getSession(boolean create)
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()
Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.
8 Object getAttribute(String name)
Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.
9 ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream.
10 String getAuthType()
Returns the name of the authentication scheme used to protect the Servlet, for example, "BASIC" or "SSL", or null if the JSP is not protected.
11 String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.
12 String getContentType()
Returns the MIME type of the body of the request, or null if the type is not known.
13 String getContextPath()
Returns the portion of the request URI that indicates the context of the request.
14 String getHeader(String name)
Returns the value of the specified request header as a String.
15 String getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
16 String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist.
17 String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request.
18 String getProtocol()
Returns the name and version of the request protocol.
19 String getQueryString()
Returns the query string that is contained in the request URL after the path.
20 String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent this request.
21 String getRemoteHost()
Returns the fully qualified name of the client that sent this request.
22 String getRemoteUser()
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()
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()
Returns the session ID specified by the client.
25 String getServletPath()
Returns the part of this request's URL that calls the JSP.
26 String[] getParameterValues(String name)
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()
Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
28 int getContentLength()
Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is unknown.
29 int getIntHeader(String name)
Returns the value of the specified request header as an int value.
30 int getServerPort()
Returns the port number on which this request was received.
31 int getParameterMap()
Encapsulates the parameters into a Map type.

HTTP Header Request Example

The following example uses the getHeaderNames() method of HttpServletRequest to read HTTP header information. This method returns an enumeration containing the header names 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 required 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")

//Extend 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 - Tutorial 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, and the corresponding web.xml configuration is:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
  <servlet>  
    <!-- Class name -->  
    <servlet-name>DisplayHeader</servlet-name>  
    <!-- Package -->  
    <servlet-class>com.tutorial.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, call the above Servlet, and access http://localhost:8080/TomcatTest/DisplayHeader to produce the following result:

[The output would display a table listing all the HTTP headers from the request.]

Servlet Form Data | Servlet Server HTTP Response

← Servlet Server ResponseServlet Form Data β†’