In development, the more HTTP requests we use are basically get, POST. Where get is used to fetch data from the server, post is used primarily to submit some form data to the server, such as file uploads. And we encountered in the use of HTTP requests in the more troublesome thing is to construct the file upload HTTP message format, although the format is relatively simple, but also more error-prone. Today we will learn the message format for HTTP post and the request to simulate file uploads via Java.
First we look at a POST request for a message, and then we'll analyze it in detail.
Post message Format
[Plain]View PlainCopy
- post/api/feed/http/1.1
- Accept-encoding:gzip
- content-length:225873
- Content-type:multipart/form-data; Boundary=ocqxmf6-jxtxomdhmog5w5ey9mgrstbp
- Host:www.myhost.com
- Connection:keep-alive
- --ocqxmf6-jxtxomdhmog5w5ey9mgrstbp
- Content-disposition:form-data; Name= "LNG"
- Content-type:text/plain; Charset=utf-8
- Content-transfer-encoding:8bit
- 116.361545
- --ocqxmf6-jxtxomdhmog5w5ey9mgrstbp
- Content-disposition:form-data; Name= "Lat"
- Content-type:text/plain; Charset=utf-8
- Content-transfer-encoding:8bit
- 39.979006
- --ocqxmf6-jxtxomdhmog5w5ey9mgrstbp
- Content-disposition:form-data; Name= "Images"; Filename= "/storage/emulated/0/camera/jdimage/1xh0e3yyfmpr2e35tdowbavrx.jpg"
- Content-type:application/octet-stream
- Content-transfer-encoding:binary
- Here is the binary data of the picture
- --ocqxmf6-jxtxomdhmog5w5ey9mgrstbp--
Here we submit a longitude, latitude, and a picture (the image data is long and messy, omitted here).
Format Analysis Request Header analysis Let's read the first line in the text format:[Plain]View PlainCopy
- post/api/feed/http/1.1
This line describes how this request is requested, that is, the Post method, the requested subpath is/api/feed/, for example, our server address is www.myhost.com, and then our full path to this request is www.myhost.com/api/feed /, finally illustrates the HTTP protocol version number is 1.1.[Plain]View PlainCopy
- Accept-encoding:gzip
- content-length:225873
- Content-type:multipart/form-data; Boundary=ocqxmf6-jxtxomdhmog5w5ey9mgrstbp
- Host:www.myhost.com
- Connection:keep-alive
These headers mean that the data returned by the server needs to use gzip compression, the content length of the request is 225873, the content type is "Multipart/form-data", the request parameter delimiter (boundary) For OCQXMF6-JXTXOMDHMOG5W5EY9MGRSTBP, the root domain of the request is www.myhost.com, and the HTTP connection is persistent (keep-alive). One of the things to note here is the delimiter, which is boundary. Boundary is used as the boundary identifier between the request parameters, such as the need for a definite boundary between parameter 1 and parameter 2, so that the server resolves to parameter 1 and parameter 2 correctly. But the delimiter is not just boundary, but the following format:--+ boundary. For example, here the boundary is OCQXMF6-JXTXOMDHMOG5W5EY9MGRSTBP, then the parameter delimiter is:[Plain]View PlainCopy
- --ocqxmf6-jxtxomdhmog5w5ey9mgrstbp
Whether or not the boundary itself has this "--", this "--" can not be omitted.
We know that the HTTP protocol uses "request-answer" mode, when using normal mode, that is, non-keepalive mode, each request/reply client and server to create a new connection, immediately after the completion of the connection (HTTP protocol is a non-connected protocol) When using Keep-alive mode (also known as persistent connection, connection reuse), the Keep-alive feature keeps the client-to-server connection active, and the keep-alive feature avoids establishing or re-establishing a connection when subsequent requests to the server occur.
As in, the left is the case of the shutdown keep-alive, each request will need to establish a connection, and then close the connection, the right is keep-alive, after the first establishment of the request to remain connected, and then the subsequent do not need to establish, close the connection each time, Enabling the Keep-alive mode is certainly more efficient and performance-based because it avoids the overhead of establishing/releasing connections.
HTTP 1.0 is turned off by default, you need to add "connection:keep-alive" in the HTTP header to enable Keep-alive;http 1.1 by default enabling Keep-alive, if you join "Connection:close", Before closing. Most browsers now use the http1.1 protocol, which means that the Keep-alive connection request is initiated by default, so whether a full keep-alive connection can be completed depends on the server setup.
The Request Entity Analysis request entity is actually the list of parameters for the HTTP POST request, with each parameter starting with the request delimiter, i.e.-+ boundary. For example, the following parameter.[Plain]View PlainCopy
- --ocqxmf6-jxtxomdhmog5w5ey9mgrstbp
- Content-disposition:form-data; Name= "LNG"
- Content-type:text/plain; Charset=utf-8
- Content-transfer-encoding:8bit
- 116.361545
Above the first behavior--OCQXMF6-JXTXOMDHMOG5W5EY9MGRSTBP, that is--plus boundary content, and finally add a newline (this line break can not be omitted), the string of newline is expressed as "\ r \ n". The second behavior is content-disposition and the parameter name, here the parameter is called LNG, that is longitude. Content-disposition is to provide a default file name when the user wants to save the requested content as a file, and we don't pay much attention here. The third behavior is Content-type, which is the type of object that the Web server tells the browser to respond to, and the specified character encoding is UTF-8. The four lines describe the transmission of the entity objects (entities) that accompany the message request and the response (response), the simple text data we set to 8bit, the file parameters we set to binary on the line. Then add two line breaks after the specific contents of the parameter. For example, the parameter content here is 116.361545. Note that each row here is wrapped with "\ r \ n", with two line breaks between the last line and the parameter content. File parameters are the same format, except that the contents of the file parameters are byte streams. Note here that the normal text parameters and file parameters are different in the following two places, because the format of the content itself is not the same. General parameters:[Plain]View PlainCopy
- Content-type:text/plain; Charset=utf-8
- Content-transfer-encoding:8bit
File parameters:[Plain]View PlainCopy
- Content-type:application/octet-stream
- Content-transfer-encoding:binary
The last line of the parameter entity is:-Plus boundary plus--, the last line, here is the format:--OCQXMF6-JXTXOMDHMOG5W5EY9MGRSTBP--。 Analog File Upload Request[Java]View PlainCopy
- public static void UploadFile (String fileName) {
- try {
- //Line break
- final String newLine = "\ r \ n";
- final String Boundaryprefix = "--";
- //Define Data separation lines
- String boundary = "========7D4A6D158C9";
- //The domain name of the server
- URL url = new URL ("www.myhost.com");
- HttpURLConnection conn = (httpurlconnection) url.openconnection ();
- //set to post
- Conn.setrequestmethod ("POST");
- //Send a POST request must have the following two lines set
- Conn.setdooutput (true);
- Conn.setdoinput (true);
- Conn.setusecaches (false);
- //Set request header Parameters
- Conn.setrequestproperty ("Connection", "keep-alive");
- Conn.setrequestproperty ("Charsert", "UTF-8");
- Conn.setrequestproperty ("Content-type", "multipart/form-data; boundary= "+ boundary);
- OutputStream out = new DataOutputStream (Conn.getoutputstream ());
- //Upload files
- File File = new file (FileName);
- StringBuilder sb = new StringBuilder ();
- Sb.append (Boundaryprefix);
- Sb.append (boundary);
- Sb.append (NewLine);
- //file parameters, photo parameter name can be arbitrarily modified
- Sb.append ("content-disposition:form-data;name=\" photo\ "; filename=\" "+ filename
- + "\" "+ newLine);
- Sb.append ("Content-type:application/octet-stream");
- //Parameter header requires two line break after setting, then the parameter content
- Sb.append (NewLine);
- Sb.append (NewLine);
- //Writes data of the parameter header to the output stream
- Out.write (Sb.tostring (). GetBytes ());
- //Data input stream for reading file data
- DataInputStream in = new DataInputStream (new FileInputStream (
- file));
- byte[] bufferout = new byte[1024];
- int bytes = 0;
- //Read 1KB data each time and write file data to the output stream
- While ((bytes = In.read (bufferout))! =-1) {
- Out.write (Bufferout, 0, bytes);
- }
- //Last Add line break
- Out.write (Newline.getbytes ());
- In.close ();
- //define the last data divider, i.e.-plus boundary plus--。
- byte[] End_data = (newLine + boundaryprefix + boundary + boundaryprefix + newLine)
- . GetBytes ();
- //write the end Mark
- Out.write (End_data);
- Out.flush ();
- Out.close ();
- //define BufferedReader input stream to read the response of the URL
- BufferedReader reader = new BufferedReader (New InputStreamReader (
- Conn.getinputstream ()));
- String line = null;
- while (line = Reader.readline ()) = null) {
- System.out.println (line);
- // }
- } catch (Exception e) {
- System.out.println ("send POST request exception!") "+ e);
- E.printstacktrace ();
- }
- }
Java analog HTTP POST request upload file