I. ANATOMY of HTTP request packets
An HTTP request packet consists of three parts.Request line + request header + request body) :
Let’s write a simple HTTP server based on socket
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
class SocketHandler implements Runnable
{
final
static String CRLF =
"\r\n";
/ / 1
private Socket clientSocket;
public SocketHandler(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
public void handleSocket(Socket clientSocket) throws IOException
{
BufferedReader in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(clientSocket.getOutputStream())),
true);
String requestHeader =
"";
String s;
while((s = in.readLine()) ! =null)
{
s += CRLF;
// 2 is important. By default, '\r\n' is removed from the result of in.readline
requestHeader = requestHeader + s;
if ( s.equals(CRLF) )
{
// 3 We get the HTTP headers; If the request body is determined from the request header, you need to continue retrieving the data
break;
}
}
System.out.println(
"Client header:");
System.out.println(requestHeader);
String responseBody =
"The client request header is: \n" + requestHeader;
String responseHeader =
"HTTP / 1.0 200 OK \ r \ n" +
"Content-Type: text/plain; charset=UTF-8\r\n"
+
"Content-Length: " + responseBody.getBytes().length +
"\r\n" +
"\r\n";
// 1. How does the browser detect the content-Length code? 2. The number of Chinese characters? The number of bytes?
System.out.println(
"Response header:");
System.out.println(responseHeader);
out.write(responseHeader);
out.write(responseBody);
out.flush();
out.close();
in.close();
clientSocket.close();
}
@Override
public void run(a)
{
try{! [Insert picture description here](HTTPS://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/0fd0f8a0950c4561995e458b83ee2171~tplv-k3u1fbpfcp-zoom-1.image)
handleSocket(clientSocket);
}
catch(Exception ex) { ex.printStackTrace(); }}}public
class MyHTTPServer
{
public static void main(String[] args) throws Exception
{
int port =
8000;
ServerSocket serverSocket =
new ServerSocket(port);
System.out.println(
"Start service, bind port:" + port);
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(
30);
/ / 5
while (
true)
{
/ / 6
Socket clientSocket = serverSocket.accept();
System.out.println(
"New connection" + clientSocket.getInetAddress() +
":" + clientSocket.getPort());
try
{
fixedThreadPool.execute(
new SocketHandler(clientSocket));
}
catch(Exception e) { System.out.println(e); }}}}Copy the code
Start the HTTP Server above, then use Google Chrome to visit http://127.0.0.1:8000/, we can know from the content of the browser response (or F12>Nettwork>Request Headers) that we actually requested the HTTP message
1.1. Request method
GET and POST are the most common HTTP methods, along with DELETE, HEAD, OPTIONS, PUT, and TRACE. However, while most current browsers only support GET and POST, Spring 3.0 provides a HiddenHttpMethodFilter that allows you to specify these special HTTP methods with the form parameter “_method” (and actually submit the form via POST). After the HiddenHttpMethodFilter is configured on the server side, Spring emulates the corresponding HTTP methods based on the values specified by the _method parameter, so that these HTTP methods can be used to map processing methods.
The eight methods defined in HTTP/1.1 are: blog.csdn.net/qq_38191191…
1.2, URL
Is the URL address corresponding to the request, which together with the Host attribute of the packet header constitutes a complete request URL.
1.3 Protocol version
Is the protocol name and version number.
1.4. Request headers
Is an HTTP packet header. The packet header contains several attributes in the format of Attribute Name: Attribute value. The server obtains client information based on the attributes.
What are header attributes? We may as well illustrate with a short story.
It’s nearly noon, Zhang Sanfeng doesn’t want to go to the canteen, so he calls for take-out: Boss, I want a [fish fragrant pork], I want to send it to me before 12:30, I’m in the R&D department of Jianghu Lake Company, my name is Zhang Sanfeng. Here, you want [yu Xiang Rou si] to be equivalent to the HTTP message, while “send by 12:30”, you call “Zhang Sanfeng” and other messages are equivalent to the HTTP header. They are ancillary information that will help you close the deal with the restaurant owner. Both the request HTTP packets and the response HTTP packets have several packet attributes, which are ancillary information to assist the client and server in the transaction.
Common HTTP request header Attribute Accept An Accept header attribute in a request packet tells the server what type of response the client accepts. The following header is equivalent to telling the server that the response type is only plain text data. Don’t send any other pictures or videos, then I will be dead
Can Accept: text/plain Accept the value of the attribute with the value of one or more of the MIME type, about the MIME type, everyone please refer to: en.wikipedia.org/wiki/MIME_t… Cookie The Cookie of the client is passed to the server through this header property. As follows:
Cookie: $Version=1; Skin=new; jsessionid=5F4771183629C9834F8382E23BE13C4C
How does the server know that multiple requests from the client belong to one Session? Notice the background of the jsessionid = 5 f4771183629c9834f8382e23be13c4c yet? Jsessionid = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID (Of course, you can rewrite the URL to attach the session ID at the end of each URL.) Referer indicates the URL from which the request came. If you search for an advertising page of a merchant through Google and you are interested in the AD page, click the mouse and send a request message to the merchant’s website. The Referer header attribute for this request message is http://www.google.com. Cache-control Controls the Cache. For example, if a request is returned, the contents of the response will be cached for a year by the client, or the contents of the response will not be cached by the client. Such as the following Settings, equivalent to let the server will return to the corresponding request response content not in the client Cache: cache-control: no – Cache other request packet header properties See also: en.wikipedia.org/wiki/List_o… HttpServletRequest: HttpServletRequest: HttpServletRequest: HttpServletRequest:
// Get the attribute name in the request message
java.util.Enumeration<java.lang.String> getHeaderNames();
// Gets the value of the header attribute with the specified name
java.lang.
String getHeader(java.lang.String name)
Copy the code
HttpServletRequest provides a VIP API for some request header attributes that are “too famous” :
// Get the Cookie in the header (read the header attribute of the Cookie)
Cookie[] getCookies() ;
// Get client localization information (read header attributes of accept-language)
java.util.
Locale getLocale(a)
// Get the Length of the request format (read the content-length header attribute)
int
getContentLength
(a);
Copy the code
HttpServletRequest can obtain the HttpSession associated with the request via getSession(). The internal mechanism is to read the JSESSIONID value of the Cookie attribute in the request header. Get the corresponding HttpSession object based on this JSESSIONID. This way, you won’t find HttpSession mysterious, you can do a similar session management yourself )
1.5. Newspaper style
It encodes component values in a page form into a format string, which holds data for multiple request parameters, in the form of param1= Value1 & Param2 =value2 key-value pairs. Not only can the message format pass the request parameters, but the request URL can also be passed via something like “/chapter15/user.html? Param1 =value1& Param2 =value2 is used to pass the request parameters.
If we break it down further, you can see a more detailed structure:
Second,Anatomy of HTTP response packets
The HTTP response message also consists of three parts (Response line + response header + response body) :
Here is an actual HTTP response message:
2.1 Response status code
Compared with the request packet, the response packet has a response status code, which tells the client the processing result of the request in a clear and unambiguous language. The HTTP response status code consists of five segments:
- 1XX message: the request has been received and is being processed.
- 2XX successfully processing generally means: the request is received, I understand what you want, the request has been accepted, has been processed and other information.
- 3xx redirects to somewhere else. It lets the client make another request to complete the processing.
- 4XX processing errors occur, and the client is responsible for such errors. For example, the client requests a non-existent resource, the client is not authorized, and access is prohibited.
- When 5XX processing errors occur, the fault is on the server. For example, the server throws an exception, the route fails, and the HTTP version is not supported.
Here are a few common status codes:
200 OK | What you want most is to handle success! |
---|---|
303 See Other | I redirect you to another page, and the destination URL is told to you by the Location of the response header. |
304 Not Modified | Tell the client that the resource you requested has not changed since you got it last time, you directly use your local cache, I am very busy, can you stop bothering me! |
404 Not Found | The last thing you want is to not find the page. If you find a page on Google and click this link to return a 404, it means that the page has been removed from the site and Google’s records are just fond memories. |
500 Internal Server Error | When you see this error, you should check the server log. It must have thrown a bunch of exceptions. Get up and fix the BUG. |
Other status code see: en.wikipedia.org/wiki/List_o… Some response codes are automatically generated by the Web application server. You can set the status code via the HttpServletResponse API:
// Set the status code, which is predefined in HttpServletResponse through a series of constants, such as SC_ACCEPTED, SC_OK
void setStatus(int sc)
Copy the code
2.2 Common HTTP response header attributes
Cache-control After the response is output to the client, the server tells the client how to Control the Cache of the response content through the header of the response. Below, the Settings of the client response content cache for 3600 seconds, which is within 3600 seconds, if the customer again to access the resources, directly from the client cache returned to the customer, don’t again from the server (of course, the functions are implemented by the client, the server is only through this attribute prompt the client “should do”, do not do, It’s up to the client, if it’s a client that claims to support HTTP, that’s how it should be implemented). Cache-Control: max-age=3600
ETag A header attribute that represents the version of the response server resource (such as a page). If a server resource changes, the ETag changes accordingly. It is a useful complement to cache-control, allowing clients to be “smarter” about when to fetch resources from the server and when to return a response directly from the Cache. For an explanation of the ETag, you can see: en.wikipedia.org/wiki/HTTP_E… . Spring 3.0 it also provide a org. Springframework. Web. Filter. ShallowEtagHeaderFilter (the content of the principle is very simple, to the JSP output MD5, so content have change the ETag changes accordingly). The ETag used to generate the response, because this really helps reduce the interaction between the request and the response. Here is an ETag: ETag: “737060 cd8c284d8af7ad3082f209582d” Location we let in the JSP page to Redirect to A certain A page, it is to let the client sends A request to A page, the need to Redirect to A URL of the page, The following header attributes redirect the client to the itEye home page: Location:blog.csdn.net/qq_26565861 Set – cookies server can Set up the client’s Cookie, its principle is through the response packet header properties:
Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
Other HTTP response message header properties more other HTTP response header message, see: en.wikipedia.org/wiki/List_o… The server can write the attributes of the response header using the HttpServletResponse API:
// Add a response header attribute
void setHeader(String name, String value)
Copy the code
Responses such as cookies and Location are blessed, and HttpServletResponse provides a VIP version of the API for them all:
// Add Cookie header attributes
void addCookie(Cookie cookie)
// Set the response header for Location and generate a status code of 303
void
sendRedirect
(String location)
Copy the code
Refer to https://blog.csdn.net/u010256388/article/details/68491509
HTTP packet Analysis (blog.csdn.net/qq_26565861…)