HTTP protocol Analysis (medium): request message and Response message

Source: Internet
Author: User
Tags nginx server htons

1. Request message Format 1.1 Server test code

Server Test Code:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>intMain () {//create communication endpoint: Socket    intSOCKFD = Socket (af_inet, sock_stream,0);if(SOCKFD <0) {perror ("socket");return-1; }//set Local address structure    structSockaddr_in my_addr; Bzero (&my_addr,sizeof(my_addr));//clearmy_addr.sin_family = af_inet;//ipv4My_addr.sin_port = htons (8000);//portMY_ADDR.SIN_ADDR.S_ADDR = htonl (inaddr_any);//IP    //bindings    intErr_log = Bind (sockfd, (structSockaddr*) &my_addr,sizeof(my_addr));if(err_log! =0) {perror ("binding"); Close (sockfd);return-1; } Err_log = Listen (sockfd,Ten);//monitor, Change the listening socket to passive    if(err_log! =0) {perror ("listen"); Close (sockfd);return-1; }printf("listen client @port =%d...\n",8000);intconnfd; CONNFD = Accept (sockfd, null, null);//waiting for connection    Charbuf[8*1024x768] = {0}; Read (connfd, buf,sizeof(buf));printf('%s ', buf); while(1) {NULL; }return 0;}

Browser input URL Address:

The terminal starts the server program and tests the HTTP request message:

1.2 Request Message Format description

The HTTP request message consists of the request line, the request header, the blank line, the request packet Body 4 parts, as shown in:

1) Request Line
The request line consists of the method field, the URL field, and the HTTP Protocol version field 3 sections, separated by a space. Common HTTP Request methods are get, POST.

GET:

    • The Get method is used when the client wants to read a resource from the Server. The GET method requires the server to place the url-positioned resource in the data portion of the response message, which is sent back to the client, requesting a resource from the Server.
    • When using the Get method, the request parameter and the corresponding value are appended to the URL, using a question mark ("?") The end of the URL represents the beginning of the request parameter and the pass parameter length is limited, so the Get method is not suitable for uploading Data.
    • When you get a Web page by the get method, the parameters are displayed on the Browser's address bar, so the confidentiality is Poor.
GET / HTTP/1.1Host192.168.11.80:9889User-AgentMozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0Accepttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Languageen-US,en;q=0.5Accept-Encodinggzip, deflateConnectionkeep-alive

POST:

    • When the client provides more information to the server, the Post method can be used to submit data to the server, such as completing the submission of form data and submitting the data to the server for Processing.
    • Get is typically used to get/query resource information, and POST comes with user data, which is typically used to update resource Information. The Post method encapsulates the request parameters in the HTTP request data and is not limited in length because the data that is carried by the post, in the request body of the http, appears as a name/value and can transmit large amounts of Data.
Post/search http/1.1 accept:image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel,  application/vnd.ms-powerpoint,application/msword, application/x-silverlight, application/x-shockwave-flash, */* Referer:<a href="http://www.google.cn/">http://www.google.cn/</a>ACCEPT-LANGUAGE:ZH-CN accept-encoding:gzip, deflate user-agent:mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;. NET CLR 2.0.50727; Theworld) Host:<a href="http://www.google.cn">www.google.cn</a>Connection:keep-alive cookie:pref=id=80a06da87be9ae3c:u=f7167333e2c3b714:nw=1:tm=1261551909:lm=1261551917:s= ybycq2wpfefs4v9g; Nid=31=ojj8d-iygaetsxlgajmqsjvhcspkvijrb6omjamnrsm8lzhky_ Ymfo2m4qmrkch1g0iqv9u-2hfbw7bufwvh7pgarub0rnhcju37y-fxlrugatx63jlv7cwmd6ub_o_r hl=zh-CN&source=hp&q= Domety

2) Request Header
The request header adds some additional information to the request message, consisting of a "name/value" pair, separated by a colon between each row and the name and Value.

The request header notifies the server that there is information about the client request, and the typical request headers are:

Request Header meaning
User-agent Requested browser type
Accept A list of response content types that the client can recognize, the asterisk "*" is used to group types by scope, and " / " indicates that all types are acceptable, and "type/*" indicates that all subtypes of type types are acceptable
Accept-language Natural language acceptable to the client
Accept-encoding Client-acceptable encoding compression format
Accept-charset Acceptable answers to the character set
Host The host name of the request, which allows multiple domain names to be located in the same IP address as the virtual host
Connection Connection mode (close or Keepalive)
Cookies stored in the client extension field, sending a cookie belonging to that domain to the service side of the same domain name

3) Blank Line
The last request header is followed by a blank line that sends a carriage return and a newline character, notifying the server that the request header is no longer available.

4) Request Package Body
The request package body is not used in the get method, but is used in the post Method.
The Post method is useful for situations where a customer needs to fill out a form. The most commonly used is the package body type Content-type and the package body length content-length associated with the request package Body.

2. Response Message Format 2.1 Client test code

To start the Nginx server:

To write a client program:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>intMain () {//create communication endpoint: Socket    intSOCKFD = Socket (af_inet, sock_stream,0);//set the server address structure body    structSockaddr_in server_addr; Bzero (&server_addr,sizeof(server_addr));//initialize Server Addressserver_addr.sin_family = af_inet;//IPv4Server_addr.sin_port = htons ( the);//nginx Server listening PortInet_pton (af_inet,"192.168.31.109", &server_addr.sin_addr);//server IP     //active Connection Server    intErr_log = Connect (sockfd, (structSockaddr*) &server_addr,sizeof(server_addr));if(err_log! =0) {perror ("connect"); Close (sockfd);return-1; }//http Request packet    Charsend_buf[] ="get/mike.html http/1.1\r\n"        "accept:image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/ x-ms-xbap, */*\r\n "        "accept-language:zh-hans-cn,zh-hans;q=0.8,en-us;q=0.5,en;q=0.3\r\n"        "user-agent:mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0;. Net4.0c;. net4.0e;. NET CLR 2.0.50727;. net CLR 3.0.30729;. net CLR 3.5.30729) \ r \ n "        "accept-encoding:gzip, deflate\r\n"        "host:192.168.31.109:8000\r\n"        "connection:keep-alive\r\n"        "\ r \ n";//send HTTP Request PacketSend (sockfd, send_buf,sizeof(send_buf)-1,0);//get HTTP response Messages    Charrecv_buf[8*1024x768] = {0}; Recv (sockfd, recv_buf,sizeof(recv_buf),0);printf('%s ', recv_buf);return 0;}

Enter the URL address in the browser to get the test.html Web page:

Start the program and test the HTTP success Response Message:

Enter the URL address in the browser and do not get the corresponding page:

Start the program and test the HTTP failure response Message:

2.2 Response Message Format description

An HTTP response message consists of a status line, a response header, a blank line, and a response packet body of 4 parts, as shown in:

1) status Line
The status line consists of 3 sections of the HTTP protocol version field, the status code, and the description text of the status code, separated by a space.

Status Code:
The status code consists of three digits, the first digit indicates the type of response, and the commonly used status code has five main classes as Follows:

Status Code meaning
1xx Indicates that the server has received a client request and the client can continue to send the request
2xx Indicates that the server has successfully received and processed the request
3xx Indicates that the server requires client redirection
4xx Indicates that the client request has illegal content
5xx An unexpected error occurred indicating that the server failed to process the Client's request properly

Examples of common status codes:

Status Code meaning
OK Client request succeeded
Request Request message has a syntax error
401 Unauthorized Not authorized
403 Forbidden Server denial of service
404 Not Found The requested resource does not exist
Internal Server Error Server Internal Error
503 Server Unavailable The server is temporarily unable to process client requests (may Later)



2) Response Head
The response header may include:

Response Header meaning
Location The Location response header field is used to redirect the recipient to a new position
Server server The Response header field contains the software information that the server uses to process the request and its version
Vary Indicates a list of Non-cacheable request headers
Connection Connection mode

3) Blank Line
The last response header is followed by a blank line that sends a carriage return and a newline character, notifying the server that no longer responds to the Header.

4) Response Inclusion
The text information that the server returns to the Client.

HTTP protocol Analysis (medium): request message and Response message

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.