Text Transfer Protocol HTTP Package

xiaoxiao2021-03-05  31

First, hypertext transmission protocol and HTTP package

The HTTP protocol is used to send and receive messages on the Internet. The HTTP protocol is a request-to-answer protocol-client sends a request, the server returns the response of the request, and all requests and answers are HTTP packages. The HTTP protocol uses a reliable TCP connection, and the default port is 80. The first version of HTTP is http / 0.9, and later developed to HTTP / 1.0, and now the latest version is HTTP / 1.1. HTTP / 1.1 is defined by RFC 2616.

In HTTP, the session between Client / Server is always initialized by the client by establishing a connection and sending an HTTP request package, the server does not actively contact the client or requires connection to the client. Browsers and servers can interrupt the connection at any time, for example, when browsing the webpage, you can click the "Stop" button to interrupt the current file download process, turn off the HTTP connection with the web server.

1 http request package

HTTP Request Packet (GET, POST, etc.) consists of three parts, namely: method -uri-protocol / version, request head, request body. Below is an example of an HTTP request package (GET):

Get /index.jsp http / 1.1

Accept-language: zh-cn

Connection: Keep-alive

Host: 192.168.0.106

Content-Length: 37

UserName = new_andy & password = new_andy The first line of the request package is the first line of the package is the method -uri-protocol / version: GET is the request method. According to the HTTP standard, the HTTP request can use a variety of request methods. HTTP 1.1 supports seven request methods: GET, POST, HEAD, OPTIONS, PUT, DELETE, and TRACE, etc., commonly used for requesting methods GET and POST. /Index.jsp represents the URI. URI specifies the network resources to access. HTTP / 1.1 is the version of the agreement and protocol. The last row username = new_andy & password = new_andy is a body, and the body is separated from the HTTP header. A point in which it needs to be explained here, where content-length illustrates the length of the body, and some body lengths are not illustrated at the head, just indicate transfer-encoding: chunked. See RFC 1626 about the length calculation method of the chunked type. The header of the request package will also contain a lot of useful information about the client environment and the request text, which is no longer described. 2 HTTP answer package

Similar to the HTTP request package, consisting of three parts, respectively: protocol - status code - Description, response, answer body. Below is an example of an HTTP response:

HTTP / 1.1 200 OKServer: Microsoft-IIS / 4.0Date: Mon, 3 Jan 2005 13:13:33 Gmtcontent-Type: Text / HTMLLAST-Modified: Mon, 11 Jan 2004 13:23:42 GMTCONTENTENTH: 90

Interpretation of HTTP 包示 </ title> </ head> <body> Hello World! </ body> </ html></p> <p>The first line of the HTTP response package is similar to the first line of the HTTP request, indicating that the protocol used is HTTP 1.1, and the server processing requested status code 200. The response should also contain many useful information as the request head, such as server type, datetime, content type, and length. The body of the response is the HTML page returned by the server. The response head and the body are also separated by CRLF. Second, the Socket class is represented by the Java.Net.Socket class (client) or java.net.serversocket class (client) or java.net.serversocket class (client) or java.net.serversocket class (client). The application sends or reads data from the network via endpoints. The application on two different machines is transmitted and received by network connection, thereby implementing communication. To send an HTTP package to another application, you must first know the port number of the other party's IP address and its communication endpoint. The Socket class represents the client, which is an endpoint that is temporarily created when connecting the remote server. The ServerSocker class represents the server side. After it starts, wait for a connection request from the client; once the request is received, ServerSocket creates a socket instance to process communication with the client. For server applications, we don't know when the client application is trying to connect to the server, and the server must have been in the state of waiting. The following is a form of ServeSocket provides four constructors, a commonly used constructor is: public serversocket (INT port, int backlog, inetaddress bindingaddress); Parameters: port specifies the server-side port; backlog is a connection request The maximum queue length, once exceeded this length, the server endpoint begins to reject the client's connection request. BindingAddress is an instance of java.net.inetaddress and specifies the binding IP address. After creating a ServerSocket instance, call its Accept method to wait for the incoming connection request. Only when the connection request appears, the Accept method will return, and its return value is an instance of a socket class. Subsequently, this Socket object can be used to communicate with the client. The Socket class has many constructor, commonly: public socket (String Host, INT Port). The parameter is the host name (IP address or domain name) and port number. Parameter Host is the name or IP address of the remote machine, and Port is the port number of the remote application. After successfully created an instance of the Socket class, we can use it to send and receive data-based data, and the data is typically HTTP package. To send a byte stream, you first want to call the GetputStream method for the Socket class to get a java.io.outputstream object; receive byte streams from the other end of the connection, first to call the GetInputStream method for the Socket class to get a java.io.inputstream object. . The following code snippet creates a socket with a local HTTP server (127.0.0.1 representative of the IP address of the local host), send an HTTP request package to prepare a response to the server.</p> <p>Socket socket = new Socket ( "127.0.0.1", "80"); OutputStream os = socket.getOutputStream (); InputStream ins = socket.getInputStream (); StringBuffer sb = new StringBuffer (); sb.append ( "GET / INDEX.JSP http / 1.1 / r / n "); // Notes / R / N is the carriage return SB.Append (" Accept-language: en-cn / r / n "); Sb.Append (" Connection: Keep-alive / r / n "); sb.append (" Host: 192.168.0.06/r/N "); Sb.Append (" Content-Length: 37 / R / N "); sb.append (" / R / N "); sb.append (" username = new_andy & password = new_andy / r / n "); sb.append (" / r / n "); // Send an HTTP request package Os.Write to the web server (SB .tostring (). getBytes ()); server-side code in the general structure: while (! shutdown) {socket socket = null; try {socket = serversocket.accept (); // Waiting for the customer to send HTTP request packages // Create an HTTP Request Pack Processing Requestthread Request = New Requestthread (Socket); Request.Start (); if (Shutdown) System.exit (0);} catch (Exception E) {E.PrintStackTrace ();}}}} HTTP request package, with the request package content to generate an HTTP answer package in the server. How to analyze HTTP packages in the next section. InputStream INPUT = Socket.getinputStream (); // From this byte data stream to get the HTTP request package content outputstream output = socket.getOutputStream (); // Write this byte stream to the HTTP response package content three, read the HTTP package I design a class socketRequest that reads the HTTP package. Public class socketRequest {/ / read data from the specified Socket's InputStream</p> <p>private InputStream input; private String uri; private StringBuffer request = new StringBuffer (); // save all content for private int CONTENT_LENGTH = 0; // actual content data packet length private boolean bePost = false; private boolean beHttpResponse = false; private boolean beChucked = false; private boolean beGet = false; private byte crlf13 = (byte) 13; // '/ r' private byte crlf10 = (byte) 10; // '/ n'public SocketRequest (InputStream input) {this. INPUT = INPUT; PUBLIC SocketRequest (socket socket) {this.input = socket.getinputstream ();</p> <p>Public void readdata () {// parsing data readheader (); // head</p> <p>IF (bechucked) / / for chucked {Int chucksize = 0; while ((chucksize = getchucksize ())> 0) // multiple chucked {readlendata (chucksize 2); // Read fixed length data} Readlendata (2 ); // last 2} if (content_length> 0) {readlendata (content_length); // Read fixed length data} URI = ""; // Parseuri (new string (request));} private void Readlendata INT size) // Read the fixed length data {intread = 0; // The number of Try {int available = 0; // infut.available (); // Readable IF (available> (Size-readed) ) AVAILABLE = Size-readed; while (available == 0) {// Waiting to have data readable available = input.available (); // readable number} if (available> (Size-readed )) Available = Size-readed; // size-readed - Remaining number IF (Available> 2048) Available = 2048; // size-readed - Remaining number byte [] buffer = new byte [available]; int = INPUT.READ (BUFFER); Request = Request.Append (New String (Buffer, 0, Reading); // Byte array adds readed =read; // read characters}} catch (ioException e) {system.out .println ("Read Readlendata Error! ");}} Private void readheader () // read the header and get the size {byte [] CRLF = New byte [1]; int crlfnum = 0; // The number of carriages that has been connected will change CRLFNUM = 4 End Try {whele (invut.read (CRLF)! = - 1) // Read head {if (CRLF [0] == CRLF13 || CRLF [0] == CRLF10) {CRLFNUM ;} else {crlfnum = 0;} // is not clear request = request.append (new string (crl, 0, 1)); // BYTE array add IF (crlfnum == 4) Break;}} catch (ooException e) {system .out.println ("Read http header error!"); return; string tempstr = (new string). TouPpercase ();</p> <p>/ / Here I only deal with GET and Post method string strmethod = tempstr.substring (0, 4); if (strMethod.equals ("get") // {beget = true;} else} (Strmethod.equals) "Post")) {bepost = true; getContentlen_chucked (Tempstr);} else {system.out.println ("Does not support HTTP package type");} // Other types No support} private void getContentlen_chucked (String) Tempstr) // Get length content-length or whether chunked type {string ss1 = "Content-length:"; string ss2 = new string ("Transfer-encoding: chunked"); int CLINDEX = Tempstr.Indexof (SS1); INT chuckIndex = Tempstr.indexof (s2); // is chunked type byte requst [] = Tempstr.getbytes (); if (clindex! = - 1) {// From CLINDEX 1 to / R / n StringBuffer SB = New stringbuffer (); for (INT i = (Clindex 16) ;; i ) {if (Requst [i]! = (byte) 13 && Requst [i]! = (byte) {sb.append ( CHAR) REQUST [I]);} Else Break;} content_length = integer.parseint (sb.tostring ()); // The official HTML file size //system.out.pr Intln ("Content_length ==" Content_length);} if (ChuckIndex! = - 1) bechucked = true;} private int getchucksize () // chuck size {byte [] CRLF = New Byte [1]; stringbuffer sb1 = new Stringbuffer ();</p> <p>INT CRLFNUM = 0; // The number of carriages that has been connected is CRLFNUM = 4 to end the head {while (Input.read (CRLF)! = - 1) // Read the header {IF (CRLF [0] = = CRLF13 || CRLF [0] == CRLF10) {CRLFNUM ;} else {crlfnum = 0;} // is not clear Sb1.Append ((char) CRLF [0]); request = request.append (new string CRLF, 0, 1)); // BYTE array add IF (CRLFNUM == 2) Break;}} catch (ooexception e) {system.out.println ("Read http package error!"); return 0;} Return Integer.Parseint ((sb1.toString ()). Trim (), 16); // 16 In-input, filtering, whether it is a HTTP package for the target server Private String Parseuri (String RequestString) {int index1, index2; index1 = requestString.indexOf ( ''); if (index1 = -1!) {index2 = requestString.indexOf ( '', index1 1); if (index2> index1) return requestString.substring ( Index1 1, Index2);} return null;} public string getdata () {return request.toString ();}}</p> <p>Use this class: socketRequest request = new socketRequest (socket); // socket is the Socket instance request.readData (); // read data request.getdata (); why do I use so big? Force to read, especially because the socket connection is transmitted during transmission, the delay in the network may often occur, and only some of the data may only be obtained from the inputStream when the server is received. At that time, only incomplete data or errors can be obtained. There are many ways when reading bytes from inputStream: often intread () and int in (byte [] b). When using read (Byte []), programmers often make mistakes, because in the network environment, the amount of data read is not necessarily equal to the size of the parameters. I hope that this article will bring you some help. Author: Yuan Wencong QQ: 7684315 MSN: new_andy@msn.com</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-33708.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="33708" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.037</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '7RAeiOwp0tqUgovUfpx2JlSyJoa3i001CJtymZzNaYK6xZuCDmV_2FOfyjQ8pjSqSrD2yB0Av_2B9nTxvZbjJSqQEQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>