Java Web Foundation 2HTTP Protocol Knowledge Point Summary

Source: Internet
Author: User
Tags base64 http file upload java web

 

I. HTTP protocol Basics

1. Definition: HTTP is a TCP connection-based browser-to-server communication protocol. (That is, the transport layer first uses the TCP three handshake to establish the connection, thus the HTTP communication)

2. Connection principle: Advanced line TCP establishes an end-to-end connection and then sends and accepts HTTP messages.

TCP (Socket) is an end-to-end connection that is used to locate the specific running program for two hosts on the network by IP address and port number. Therefore, the HTTP connection initiates a TCP connection to establish a connection to the server software and then sends and accepts HTTP message content. So when you run the gripper, when you open the Web page, you see a TCP connection and an HTTP connection. When using the HTTP 1.0 version, a TCP connection is made every time a Web page is opened. Each connection to TCP consumes system resources (both CPU and memory). HTTP1. the 1 version of TCP connection is persistent and the request header default setting is Keep-alive=true. This situation transmits multiple requests with one copy of the TCP connection. Typical is AJAX applications.

3. Analog Send/Respond HTTP messages

Therefore: it is entirely possible to use the Java Socket Writer program to impersonate the client browser to send HTTP requests. Of course, you can implement the file download function of the client software.

The code is as follows: simulate sending HTTP requests

  1. Socket s = new socket (Inetaddress.getlocalhost (), 8080);
  2. OutputStreamWriter OSW = new OutputStreamWriter (S.getoutputstream ());
  3. StringBuffer sb = new StringBuffer ();
  4. Sb.append ("get/httpstream/gb2312.jsp http/1.1\r\n");
  5. Sb.append ("host:localhost:8088\r\n");
  6. Sb.append ("connection:keep-alive\r\n");
  7. Note that this is the key to the key and forget to let me engage in this for half an hour. Here must be a carriage return line, indicating the end of the message, or the server will wait
  8. Sb.append ("\ r \ n");
  9. Osw.write (Sb.tostring ());
  10. Osw.flush ();

Analog Read HTTP response

  1. InputStream is = S.getinputstream ();
  2. String line = null;
  3. int contentlength = 0; Message length sent back by the server
  4. Read all requests sent over the server header information
  5. do {
  6. Line = ReadLine (IS, 0);
  7. If a content-length message header is removed
  8. if (Line.startswith ("Content-length")) {
  9. ContentLength = Integer.parseint (Line.split (":") [1].trim ());
  10. }
  11. Print Request Department Information
  12. System.out.print (line);
  13. If a separate carriage return line is encountered, the request header ends
  14. } while (!line.equals ("\ r \ n"));
  15. --the body of the loss message
  16. System.out.print (ReadLine (IS, contentlength));
  17. Close the stream
  18. Is.close ();
  19. } catch (Unknownhostexception e) {
  20. E.printstacktrace ();
  21. } catch (IOException e) {
  22. E.printstacktrace ();
  23. }
  24. }
  25. The ReadLine () method implementation is not given, because I feel that the reading method is inefficient. Interested can refer to the original author code.

(The code goes from http://blog.csdn.net/a9529lty/article/details/7174265, thanks to the original author)

Two. About HTTP file upload and download

Socket analog HTTP Upload file code

  1. File file=new file ("c:/Snow Wolf Commando. jpg");
  2. To read a file as a string
  3. String picstring=readfileasstring (file.tostring ());
  4. UrlEncode
  5. picstring="Picdata=" +urlencoder.encode (picstring, "UTF-8");
  6. String url="http://localhost:8080/Test/index.jsp?uid=1&username=test&auth=  098f6bcd4621d373cade4e832627b4f6 ";
  7. Socket socket =new socket (inetaddress.getbyname (URL),80);
  8. DataOutputStream dos=New DataOutputStream (Socket.getoutputstream ());
  9. String message=""
  10. +"POST" +url+"http/1.1 \ r \ n"
  11. +"Host:test.lingye.com \ r \ n" +"Accept: */* \ r \ n"
  12. +"cache-control:no-cache \ r \ n" +"user-agent:msie6.0; \ r \ n "
  13. +"content-type:application/x-www-form-urlencoded \ r \ n"
  14. +"Content-length:" +picstring.length () +"\ r \ n"
  15. +"Connection:close \r\n\r\n"//header with two \ n as end-of-sign
  16. +picstring+"\ r \ n"; Post Data
  17. byte buffer[]=message.getbytes ();
  18. Dos.write (buffer);
  19. Dos.flush ();
  20. Dos.close ();
  21. The above only sends the operation
  22. Socket.close ();
  23. } catch (Exception e) {
  24. E.printstacktrace ();
  25. }
  26. }
  27. Server-side servlet
  1. Public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
  2. String picdata =request.getparameter ("picdata");
  3. Note that the picdata here is the image corresponding to the Encode encoding method, the same encoding and the same decoding method
  4. Base64decoder base64=New Base64decoder ();
  5. 64-bit decoding
  6. Byte[] Buffer=base64.decodebuffer (picdata);
  7. Write in File
  8. FileOutputStream fos=New FileOutputStream ("c:/Snow Wolf Commando 1.jpg");
  9. Fos.write (buffer);
  10. Fos.flush ();
  11. Fos.close ();
  12. fos=null;
  13. }

(The code goes from http://blog.sina.com.cn/s/blog_5da93c8f0100vj3v.html, thanks to the author)

As you can see, the Java language can write a browser, of course, the browser function is very complex. The browser parses the HTML code of the HTTP response and forms the page we see.

Note that the socket simulates the HTTP request and response method, it can be seen that the read input stream/output stream is obtained in a socket connection, that is, each TCP connection (3 times after the handshake), there will be a corresponding input and output. You can send and receive data using this input and output stream.

4. Detailed description of the agreement

Refer to Http://www.cnblogs.com/li0803/archive/2008/11/03/1324746.html, the details of the agreement are explained in detail

5. Persistent and non-persistent connections to http1.0 and http1.1

Both the http/1.0 and http/1.1 have non-persistent connections (non-persistent connection) and continuous connection (persistent connection) functionality. A non-persistent connection is when a TCP connection server is started to transfer an object to the client, whereas a persistent connection means that the server can send multiple objects to the client on the same TCP connection. The default setting for http/1.0 is non-persistent, and the default setting for http/1.1 is persistent connection.

With http/1.0, if you open a Web page that contains an HTML file and 10 inline image objects, HTTP will establish 11 TCP connections to transfer the files from the server to the client. With http/1.1, if you open the same file, HTTP establishes a TCP connection to transfer the file from the server to the client. Using a TCP connection to deliver an object is inefficient, which is reflected in the following areas:

(1) Each TCP connection must be established and disconnected. A three-way communication connection (Three-way handshake) is required to establish a connection between the client and the server, and the server disconnects the TCP connection after the object is delivered. The resources that are used to consume the CPU when the connection is established and disconnected. If you use a single connection instead of 11 connections, the CPU time of the client and server can be significantly reduced.

(2) For each connection, both the client and the server must be assigned a send and receive cache. This means that the memory resources of the client and server are affected, which also consumes CPU time.

(3) for a file consisting of a large number of objects, TCP's low-speed startup algorithm (slow start-up algorithm) restricts the speed at which the server transmits objects to the client. With http/1.1, most objects can be delivered at the maximum rate possible.

Because http/1.1 allows persistent connections, all objects in the file can be routed on the same TCP connection. http/1.1 also allows multiple message requests to be sent before the client receives a message response from the server, called pipelined requests (pipelined request).

(This paragraph is transferred from http://blog.chinaunix.net/uid-9681606-id-1998549.html, thanks to the author's contribution)

6.

Why is there no entity content in the Get method request message? You cannot include entity content in a request message that uses get, only the content of the entity can be included in a post-mode request message
, I have a question, why is there no entity content in the request message for the Get method, what is the value of the entity content in the request message, the parameter is not the entity content?  Answer:
This friend may not know much about the HTTP protocol a complete request message contains a number of message headers for a request line, as well as entity content, where some of the message headers and entity contents are optional!!!! And in the Get and post mode as a form form. Because the Get method does not contain the entity content, the entity content (that is, the form's data) appears as an argument after the URL address post is the entity content, it puts the form data inside the entity content, with ' entity content ' The form of the transfer of the data volume is limited generally below 1kb, and the Post method is much larger! You can also see the difference between the parameters and the entity content.;;

Java Web Foundation 2HTTP Protocol Knowledge Point Summary

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.