English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
When the browser requests a web page, it sends specific information to the web server, which cannot be read directly because this information is transmitted as part of the header of the HTTP request. You can view HTTP Protocol Learn more related information.
The following are important headers from the browser side that you can frequently use in web programming:
Header Information | Description |
---|---|
Accept | This header information specifies the MIME types that browsers or other clients can handle. Value image/png or image/jpeg are the most common two possible values. |
Accept-Charset | This header information specifies the character set that the browser can use to display information. For example, ISO-8859-1. |
Accept-Encoding | This header information specifies the encoding types that the browser knows how to handle. Value gzip or compress are the most common two possible values. |
Accept-Language | This header information specifies the preferred language of the client, in which case, the Servlet will produce results in multiple languages. For example, en, en-us, ru, etc. |
Authorization | This header information is used by the client to identify itself when accessing password-protected web pages. |
Connection | This header information indicates whether the client can handle persistent HTTP connections. Persistent connections allow clients or other browsers to retrieve multiple files through a single request. Value Keep-Alive Means that a persistent connection has been used. |
Content-Length | This header information is only applicable to POST requests and gives the size of the POST data (in bytes). |
Cookie | This header information returns the cookies sent to the browser previously to the server. |
Host | This header information specifies the host and port in the original URL. |
If-Modified-Since | This header information indicates that the client wants the page that has been changed after the specified date, only if there are no new results to use. If there are no new results available, the server will send a 304 Code, indicating Not Modified header information. |
If-Unmodified-Since | This header information is If-Modified-The opposite of Since, it specifies that the operation will only be successful if the document is earlier than the specified date. |
Referer | This header information indicates the URL of the Web page being pointed to. For example, if you are on a web page 1, clicks a link to a web page 2, when the browser requests a web page 2 When 1 The URL will be included in the Referer header information. |
User-Agent | This header information identifies the browser or other client that made the request and can return different content to different types of browsers. |
The following methods can be used in Servlet programs to read HTTP headers. These methods are accessed through HttpServletRequest Object Available.
Serial Number | Method & Description |
---|---|
1 | getCookies() Returns an array containing all the Cookie objects sent by the client with this request. |
2 | getAttributeNames() Returns an Enumeration containing the names of the attributes provided for the request. |
3 | getHeaderNames() Returns an Enumeration containing all the header names included in the request. |
4 | getParameterNames() Returns an Enumeration of String objects containing the names of the parameters included in the request. |
5 | getSession() Returns the current session associated with the request, or if the request does not have a session, creates one. |
6 | getSession(boolean create) Returns the current HttpSession associated with the request, or if there is no current session and the create parameter is true, returns a new session. |
7 | getLocale() Based on Accept-Language header, returns the preferred locale the client accepts for content. |
8 | Object getAttribute(String name) Returns the value of the named attribute as an object, or null if an attribute with the given name does not exist. |
9 | ServletInputStream getInputStream() Retrieves the request body in binary data form using ServletInputStream. |
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 unknown. |
13 | String getContextPath() Returns the request URI part that indicates the request context. |
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 used for the request, such as GET, POST, or PUT. |
16 | String getParameter(String name) Returns the value of the request parameters as a string, or null if the parameter does not exist. |
17 | String getPathInfo() Returns any additional path information related to the URL sent by the client when the request is made. |
18 | String getProtocol() Returns the name and version of the request protocol. |
19 | String getQueryString() Returns the query string included in the request URL after the path. |
20 | String getRemoteAddr() Returns the Internet Protocol (IP) address of the client 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 has been authenticated, or null if the user has not been authenticated. |
23 | String getRequestURI() A part of the request's URL is returned from the query string in the protocol name to the first line of the HTTP request. |
24 | String getRequestedSessionId() Returns the session ID specified by the client. |
25 | String getServletPath() Returns a part of the URL of the request that calls the JSP. |
26 | String[] getParameterValues(String name) Returns an array of String objects containing the values of all the given request parameters, or returns 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 returns if the length is unknown. -1. |
29 | int getIntHeader(String name) Returns the value of the specified request header as an int value. |
30 | int getServerPort() Returns the port number of the request received. |
31 | int getParameterMap() Wrap the parameters into a Map type. |
The following example uses HttpServletRequest's getHeaderNames() Method to read HTTP header information. This method returns an enumeration that contains header information related to the current HTTP request.
Once we have an enumeration, we can iterate through the enumeration in a standard way, using hasMoreElements() Method to determine when to stop, using nextElement() Methods to get the name of each parameter.
//Import the 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") //扩展 HttpServlet 类 public class DisplayHeader extends HttpServlet { // 处理 GET 方法请求的方法 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "HTTP Header 请求示例 - 基础教程网示例"; 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 名称</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> } // Method to handle POST method requests 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 as follows:
<?xml version="1.0" encoding="UTF-8"?> </web-app> </servlet> <!-- Class name --> <servlet-name>DisplayHeader</servlet-name> <!-- The package it is located in --> <servlet-</class>com.w3codebox.test.DisplayHeader</servlet-<class> </</servlet> <servlet-mapping> <servlet-name>DisplayHeader</servlet-name> <!-- The visited URL --> <url-pattern>/TomcatTest/DisplayHeader</url-pattern> </servlet-mapping> </web-app>
Now, call the above Servlet, access http://localhost:8080/TomcatTest/DisplayHeader The following results will be produced: