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 information | Description |
---|---|
Accept | This 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-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 type 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 clients to identify themselves when accessing password-protected web pages. |
Connection | This 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-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 to the server. |
Host | This header specifies the host and port in the original URL. |
If-Modified-Since | This 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-Since | This 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. . |
Referer | This 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-Agent | This 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 number | Method & Description |
---|---|
1 | Cookie[] getCookies() Returns an array containing all Cookie objects sent by the client for this request. |
2 | Enumeration getAttributeNames() Returns an enumeration containing the attribute names available for this request. |
3 | Enumeration getHeaderNames() Returns an enumeration containing all header names included in the request. |
4 | Enumeration getParameterNames() Returns an enumeration of String objects containing the names of the parameters included in this request . |
5 | HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, then Create. |
6 | HttpSession 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. |
7 | Locale getLocale() Based on the Accept-Language header, returns the client's preferred locale for accepting content. |
8 | Object 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. |
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, 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 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 portion of the request URI that indicates the request context. |
14 | String getHeader(String name) Returns the value of the specified request header in string form. |
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 in string form, or if the parameter does not exist Return null. |
17 | String getPathInfo() When the request is made, return any additional paths related to the URL sent by the client information. |
18 | String getProtocol() Returns the name and version of the requested 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 the client sending the request. |
21 | String getRemoteHost() Returns the fully qualified name of the client that sent the request. |
22 | String 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. |
23 | String getRequestURI() Returns the query string from the protocol name until the first line of the HTTP request. Part of the requested URL. |
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 the JSP. |
26 | String[] 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. |
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 the input stream, or if If the length is unknown, -1 is returned. |
29 | int getIntHeader(String name) Returns the value of the specified request header as an int value. |
30 | int 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
Header Name | Header value |
---|---|
accept | */* |
accept-language | en -us |
user-agent | Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; MS-RTC LM 8) |
accept-encoding | gzip, deflate |
localhost:8080 | |
Keep-Alive | |
no-cache |