Servlet client HTTP request


Release date:2023-12-13 Update date:2023-12-16 Editor:admin View counts:121

Label:

Servlet client HTTP request

When a browser requests a web page, it sends specific information to the Webserver that cannot be read directly because it is transmitted as part of the header of the HTTP request. You can check the HTTP protocol for more information.

The following is important header information from the browser side, which you can use frequently in Web programming:

Header information

Description

Accept

This header information specifies the type of MIME that the browser or otherclient can handle. The value image/png or image/jpeg are the two most common possible values.

Accept-Charset

This header information specifies the character set that the browser can useto display the information. For example, ISO-8859-1.

Accept-Encoding

This header information specifies the type of encoding that the browser knows how to handle. The value gzip or compress are the two most common possible values.

Accept-Language

This header information specifies the preferred language of the client, in which case Servlet produces results in multiple languages. For example, en, en-us, ru, and so on.

Authorization

This header information is used for clients to identify themselves when visiting password-protected web pages.

Connection

This header indicates whether the client can handle persistent HTTP connections. Persistent connections allow clients or other browsers to retrieve multiple files through a single request. A value of Keep-Alive means that a persistent connection is used.

Content-Length

This header information applies only to POST requests and gives the size of the POST data in bytes.

Cookie

This header returns the cookies that was previously sent to the browser to the server.

Host

This header information specifies the host and port in the original URL.

If-Modified-Since

This header information represents the page that the client wants only if the page has changed after the specified date. If no new results are available, the server sends a 304code indicating the Not Modified header information.

If-Unmodified-Since

This header information is the opposite of If-Modified-Since, which specifies that the operation will succeed only if the document is earlier than the specified date.

Referer

This header information indicates the URL of the Web page you are pointing to. For example, if you click a link to page 2 on page 1, the URL of page 1 will be included in the Referer header information when the browser requestspage 2.

User-Agent

This header information identifies the browser or other client that made therequest and can return different content to different types of browsers.

The method of reading HTTP header

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

Serial number

Method & description

1

Cookie[] getCookies() returns an array of all the Cookie objects that the client sent the request.

2

Enumeration getAttributeNames() returns an enumeration containing the property names available to the request.

3

Enumeration getHeaderNames() returns an enumeration containing all the header names contained in the request.

4

Enumeration getParameterNames() returns an enumeration of String objectscontaining the names of the parameters contained in the request.

5

HttpSession getSession() returns the current session session associated with the request, or if the request does not have a session session, create one.

6

HttpSession getSession(boolean create) returns the current HttpSession associated with the request, or a new session session if there is no currentsession and the creation is true.

7

Locale getLocale() returns the preferred locale for the client to acceptcontent based on the Accept-Language header.

8

Object getAttribute(String name) returns the value of a named property as an object, or null if no property of the given name exists.

9

ServletInputStream getInputStream() use ServletInputStream to retrieve the body of the request as binary data.

10

String getAuthType() 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() returns the name of the character encoding used in the request body.

12

String getContentType() returns the MIME type of the request body, or null if the type is not known.

13

String getContextPath() returns the URI part of the request indicating 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 requested HTTP method, for example, GET, POST, or PUT.

16

String getParameter(String name) returns the value of the request parameter as a string, or null if the parameter does not exist.

17

String getPathInfo() when the request is made, any additional path information related to the URL sent by the client is returned.

18

String getProtocol() returns the name and version of the request protocol.

19

String getQueryString() returns the query string contained in the request URL after the path.

20

String getRemoteAddr() returns the Internet Protocol (IP) address of theclient that sent the request.

21

String getRemoteHost() returns the fully qualified name of the client that sent the request.

22

String getRemoteUser() returns the logged-in user who made the request if the user is authenticated, or null if the user is not authenticated.

23

String getRequestURI() returns a portion of the requested URL in the query string from the protocol name to the first line of the HTTP request.

24

String getRequestedSessionId() returns the session session ID specified by the client.

25

String getServletPath() returns part of the URL of the request that called JSP.

26

String[] getParameterValues(String name) returns an array of string objects containing the values of all given request parameters, or null if the parameter does not exist.

27

boolean isSecure() returns a Boolean value indicating whether the request uses a secure channel, such as HTTPS.

28

int getContentLength() returns the length of the request body in bytes and provides an input stream, or-1 if the length is unknown.

29

int getIntHeader(String name) returns the value of the specified requestheader as an int value.

30

int getServerPort() returns the port number on which the request was received.

31

int getParameterMap() encapsulate the parameter into a Map type.

HTTP Header request instance

The following example uses the HttpServletRequest of getHeaderNames() method to read the HTTP header information. This methodreturns an enumeration containing header information related to the currentHTTP request.

Once we have an enumeration, we can loop through it in a standard way, usingthe hasMoreElements() method to determine when to stop, using 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")

//Extend HttpServlet Class
public class DisplayHeader extends HttpServlet {

    // Method for handling GET method requests
    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 - Rookie 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 for handling POST method requests
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

The above test examples are located under the TomcatTest project, and the corresponding web.xml configured to:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <!-- Class name -->
    <servlet-name>DisplayHeader</servlet-name>
    <!-- The package it is in -->
    <servlet-class>com.runoob.test.DisplayHeader</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DisplayHeader</servlet-name>
    <!-- Visited website -->
    <url-pattern>/TomcatTest/DisplayHeader</url-pattern>
  </servlet-mapping>
</web-app>

Now, call the Servlet above to access http://localhost:8080/TomcatTest/DisplayHeader, the following results will be generated:

Image0

Powered by TorCMS (https://github.com/bukun/TorCMS).