Servlet client HTTP request


When a browser requests a web page, it sends certain information to the web server, which cannot be read directly because it is transmitted as part of the headers of the HTTP request. You can check out 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 informationDescription
AcceptThis header specifies the MIME types that the browser or other client can handle. The values ​​image/png or image/jpeg are the two most common possible values.
Accept-CharsetThis header specifies the character set that the browser can use to display information. For example ISO-8859-1.
Accept-EncodingThis header specifies the encoding type that the browser knows how to handle. The values ​​gzip or compress are the two most common possible values.
Accept-LanguageThis 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.
AuthorizationThis header is used by clients to identify themselves when accessing password-protected web pages.
ConnectionThis header indicates whether the client can handle persistent HTTP connections. Persistent connections allow a client or other browser to retrieve multiple files with a single request. The value Keep-Alive means that persistent connections are used.
Content-LengthThis header applies only to POST requests and gives the size of the POST data in bytes.
CookieThis header returns cookies previously sent to the browser to the server.
HostThis header specifies the host and port in the original URL.
If-Modified-SinceThis header indicates that the client wants the page only if the page has changed since the specified date. If no new results are available, the server sends a 304 code indicating the Not Modified header.
If-Unmodified-SinceThis header is the opposite of If-Modified-Since, which specifies that the operation will only succeed if the document is older than the specified date. .
RefererThis header indicates the URL of the Web page pointed to. For example, if you are on web page 1 and click a link to web page 2, when the browser requests web page 2, the URL of web page 1 will be included in the Referer header information.
User-AgentThis header identifies the browser or other client making the request and can return different content to different types of browsers.

Method to read HTTP header

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

Serial numberMethod & Description
1Cookie[] getCookies()
Returns an array containing all Cookie objects sent by the client for this request.
2Enumeration getAttributeNames()
Returns an enumeration containing the attribute names available for this request.
3Enumeration getHeaderNames()
Returns an enumeration containing all header names included in the request.
4Enumeration getParameterNames()
Returns an enumeration of String objects containing the names of the parameters included in this request .
5HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, then Create.
6HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request, or if there is no current session, and If create is true, a new session is returned.
7Locale getLocale()
Based on the Accept-Language header, returns the client's preferred locale for accepting content.
8Object getAttribute(String name)
Returns the value of the named attribute in object form, if there is no one with the given name If the attribute exists, null is returned.
9ServletInputStream getInputStream()
Use ServletInputStream to retrieve the body of the request as binary data.
10String 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.
11String getCharacterEncoding()
Returns the name of the character encoding used in the request body.
12String getContentType()
Returns the MIME type of the request body, or null if the type is not known.
13String getContextPath()
Returns the portion of the request URI that indicates the request context.
14String getHeader(String name)
Returns the value of the specified request header in string form.
15String getMethod()
Returns the name of the requested HTTP method, for example, GET, POST, or PUT.
16String getParameter(String name)
Returns the value of the request parameter in string form, or if the parameter does not exist Return null.
17String getPathInfo()
When the request is made, return any additional paths related to the URL sent by the client information.
18String getProtocol()
Returns the name and version of the requested protocol.
19String getQueryString()
Returns the query string contained in the request URL after the path.
20String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client sending the request.
21String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
22String getRemoteUser()
If the user is authenticated, returns the logged in user who made the request, or if the user If authentication is not passed, null is returned.
23String getRequestURI()
Returns the query string from the protocol name until the first line of the HTTP request. Part of the requested URL.
24String getRequestedSessionId()
Returns the session session ID specified by the client.
25String getServletPath()
Returns part of the URL of the request that called the JSP.
26String[] getParameterValues(String name)
Returns an array of string objects containing all given requests The value of the parameter, or null if the parameter does not exist.
27boolean isSecure()
Returns a Boolean value indicating whether the request uses a secure channel, such as HTTPS.
28int getContentLength()
Returns the length of the request body in bytes and provides the input stream, or if If the length is unknown, -1 is returned.
29int getIntHeader(String name)
Returns the value of the specified request header as an int value.
30int getServerPort()
Returns the port number where this request was received.

HTTP Header Request Example

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

Once we have an enum, we can loop through the enum in the standard way, using the hasMoreElements() method to determine when to stop, using the nextElement() method to get the name of each parameter.

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 
// 扩展 HttpServlet 类
public class DisplayHeader extends HttpServlet {
 
  // 处理 GET 方法请求的方法
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置响应内容类型
      response.setContentType("text/html");
 
      PrintWriter out = response.getWriter();
	  String title = "HTTP Header 请求实例";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><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 名称</th><th>Header 值</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>");
  }
  // 处理 POST 方法请求的方法
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}

Now, calling the above Servlet will produce the following results:

HTTP Header Request Example

##hostlocalhost:8080connectionKeep-Alivecache-controlno-cache
Header NameHeader value
accept*/*
accept-languageen -us
user-agentMozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; MS-RTC LM 8)
accept-encodinggzip, deflate