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
Post/api/feed/http/1.1accept-encoding:gzipcontent-length:225873content-type:multipart/form-data; Boundary=ocqxmf6-jxtxomdhmog5w5ey9mgrstbphost:www.myhost.comconnection: Keep-alive--ocqxmf6-jxtxomdhmog5w5ey9mgrstbpcontent-disposition:form-data; Name= "LNG" content-type:text/plain; Charset=utf-8content-transfer-encoding:8bit116.361545--ocqxmf6-jxtxomdhmog5w5ey9mgrstbpcontent-disposition: Form-data; Name= "lat" content-type:text/plain; Charset=utf-8content-transfer-encoding:8bit39.979006--ocqxmf6-jxtxomdhmog5w5ey9mgrstbpcontent-disposition: Form-data; Name= "Images"; Filename= "/storage/emulated/0/camera/jdimage/1xh0e3yyfmpr2e35tdowbavrx.jpg" content-type:application/ Octet-streamcontent-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 AnalysisRequest Header Analysislet's look at the first line in the message format:
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 the full path of our request iswww.myhost.com/api/feed/, finally, the HTTP protocol version number is 1.1.
Accept-encoding:gzipcontent-length:225873content-type:multipart/form-data; Boundary=ocqxmf6-jxtxomdhmog5w5ey9mgrstbphost:www.myhost.comconnection: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:
--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.
< Span style= "Font-family:helvetica, Tahoma, Arial, Sans-serif; line-height:25.2000007629395px; White-space:pre; " The Enable Keep-alive mode must be more efficient and performance-free because the cost of establishing/releasing a connection is avoided .
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.
Request Entity Analysisthe 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.
--ocqxmf6-jxtxomdhmog5w5ey9mgrstbpcontent-disposition:form-data; Name= "LNG" content-type:text/plain; charset=utf-8content-transfer-encoding:8bit116.361545
Above the first act--OCQXMF6-JXTXOMDHMOG5W5EY9MGRSTBP, namely--plus boundary content,finally add a newline (this line break cannot be omitted), and the newline string is represented 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. Third actContent-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. Line Fourth describes the transmission of the entity objects (entities) that accompany the message request and response (response), and we set the simple text data to 8bit. File parameters We are 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:
Content-type:text/plain; Charset=utf-8content-transfer-encoding:8bit
file Parameters:
Content-type:application/octet-streamcontent-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
public static void UploadFile (String fileName) {try {//Line break final String newLine = "\r\ n "; Final String Boundaryprefix = "--"; Defines a data divider string boundary = "========7D4A6D158C9"; The server's domain URL url = new URL ("www.myhost.com"); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Set to post Conn.setrequestmethod ("POST"); The Send POST request must be set to the following two lines conn.setdooutput (true); Conn.setdoinput (TRUE); Conn.setusecaches (FALSE); Set the request header parameter 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 the file files = new (FileName); StringBuilder sb = new StringBuilder (); Sb.append (Boundaryprefix); Sb.append (boundary); Sb.append (NewLine); File parameters, the 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"); After the parameter header is set up, it needs two newline, then the parameter content sb.append (newLine). Sb.append (NewLine); Writes the 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; Reads 1KB data each time and writes the file data to the output stream while ((bytes = In.read (bufferout))! =-1) {out.write (bufferout, 0, bytes); }//finally add newline Out.write (Newline.getbytes ()); In.close (); Define the last data divider, i.e.-plusBoundary plus--。 Byte[] End_data = (newLine + boundaryprefix + boundary + Boundaryprefix + newLine). GetBytes (); Write the end Mark Out.write (End_data); Out.flush (); Out.close (); Defines the response of the BufferedReader input stream to read 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 (); } }
Uploading files using Apache Httpmime
/** * @param fileName Image Path */public static void Uploadfilewithhttpmime (String fileName) {//definition request ur L String uri = "www.myhost.com"; Instantiate the HTTP client HttpClient HttpClient = new Defaulthttpclient (); Instantiate the Post submission method HttpPost post = new HttpPost (URI); Add JSON parameter try {//Instantiate Parameter object multipartentity params = new multipartentity (); Picture text parameter Params.addpart ("Textparams", New Stringbody ("{' user_name ': ' My username ', ' channel_name ': ' But TD ', ' channel_address ': ' (123.4,30.6) '} ', Charset.forname ("UTF-8")); Set the file to be uploaded files = new (FileName); File parameter contents filebody filebody = new Filebody (file); Add File parameter Params.addpart ("Photo", filebody); Params.addpart ("Photoname", New Stringbody (File.getname ())); Adding parameters to the post.setentity (params) in the POST request body; Perform a POST request and haveTo the return object [to this step our request begins] HttpResponse resp = Httpclient.execute (POST); Parse returns the result of the request httpentity entity = resp.getentity (); InputStream is = Entity.getcontent (); BufferedReader reader = new BufferedReader (new InputStreamReader (IS)); StringBuffer buffer = new StringBuffer (); String temp; while (temp = reader.readline ()) = null) {buffer.append (temp); } System.out.println (buffer); } catch (Unsupportedencodingexception e) {e.printstacktrace (); } catch (Clientprotocolexception e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); } catch (IllegalStateException e) {e.printstacktrace (); } }
Httpmime.jar,Download the HttpClient package, which is included in the Httpmime.jar.
HTTP POST request message format Analysis and Java implementation file upload