Android Http Post File upload-----RFC1867 protocol

Source: Internet
Author: User
Tags http post rfc


RFC1867 Protocol Introduction
The RFC1867 protocol mainly adds the file attribute to the input tag on the basis of the HTTP protocol. At the same time, the method that defines the form must be POST, and the enctype must be multipart/form-data. Other property tags, <input type=file> tags can have a Value property to specify the default file name , can be used "size= wide, high" To specify the Size property .

Multipart/form-data

Multipart/form-data 's media content complies with multipart data flow rules as defined in RFC 1521.

It is mainly used to describe the data returned when the form is filled out. In a table consignments (which refers to HTML, and of course other applications may also use a form), there is a series of fields available for the user to fill in. Each of these fields has its own name.

In a certain form. Each of these names is unique.
Multipart/form-data consists of several parts, each with a content-disposition header, and its value is "Form-data". Its properties indicate the name of the field within the form. For example, ' content-disposition:form-data; Name= "xxxxx", where the xxxxx is the field name corresponding to the field. Suppose the field name includes non-ASCII characters. It should also be encoded in accordance with the methods specified in RFC 1522.


For all multi-part MIME types, each section has an optional Content-type, and the default value is Text/plain. Assume that the contents of the file are returned by the form fill upload. Then the input file is defined as Application/octet-stream, or, assuming you know what type it is, it is defined as the corresponding media type. If a form returns multiple files, they are returned as a combination of multipart/mixed in Multipart/form-data.
Assume that the content being delivered does not conform to the default encoding method. This section will be encoded and added with "Content-transfer-encoding" header.




Android Post upload file implementation

Android Post upload file, can be based on the RFC1867 protocol to achieve.

/** * * @param urlpath * @param params * Map < number of references > * @param fileparams * Map File type Number < parameter name, file path > * */public string Postfile (String URLPath, map<string, object> params,map<string, STRING&G T Fileparams) throws FileNotFoundException {string PREFIX = "--";//prefix string line_end = "\ r \ n";//newline string boundary = UUID . Randomuuid (). toString (); Boundary identifier URL URL; HttpURLConnection connection;try {url = new URL (urlpath); connection = (HttpURLConnection) url.openconnection ();// Set timeout time connection.setreadtimeout (readtimeout); Connection.setconnecttimeout (connecttimeout);// Request Mode Connection.setrequestmethod ("POST"); Connection.setrequestproperty ("X-requested-with", "XMLHttpRequest");// Turn on input stream connection.setdoinput (true);//turn on output stream Connection.setdooutput (true);//Turn off cache connection.setusecaches (FALSE);// Set the encoding Connection.setrequestproperty ("Charset", "Utf-8"), Connection.setrequestproperty ("Connection", "keep-alive"); Connection.setrequestproperty ("User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1);//set content type and definition Boundaryconnection.setrequestproperty ("Content-type", "multipart/form-data" + "; boundary=" + boundary);//Get output stream DataOutputStream dos = new DataOutputStream (Connection.getoutputstream ()); StringBuffer SB = null; String result = ""; String paramstr;//sends non-file parameters if (mparams! = null && mparams.size () > 0) {iterator<string> it = Mparams.keyse T (). iterator (); while (It.hasnext ()) {sb = NULL;SB = new StringBuffer (); String key = It.next (); Object value = Mparams.get (key); Sb.append (PREFIX). Append (Boundary). Append (line_end); sb.append ("Content-disposition:form-data; Name=\ ""). Append (Key). Append ("\" "). Append (Line_end). Append (line_end) sb.append (value). Append (Line_end); Paramstr = sb.tostring ();d os.write (Paramstr.getbytes ());d Os.flush ();}} PARAMSTR = null;//Send file parameters, read file stream write to post output stream if (mfileparams! = null &&!mfileparams.isempty ()) {Iterator<entry <string, string>> fileiter = Mfileparams.entryset (). iterator (); whilE (Fileiter.hasnext ()) {sb = NULL;SB = new StringBuffer (); entry<string, string> Entry = Fileiter.next (); String Filekey = Entry.getkey (); String FilePath = Entry.getvalue (); File File = new file (FilePath), if (file.exists () = = False) {throw new FileNotFoundException ();} Set the bounding mark, set the content-disposition header to the incoming file stream Sb.append (PREFIX). Append (Boundary). Append (Line_end); Sb.append (" Content-disposition:form-data; Name=\ "" + Filekey + "\"; Filename=\ "" + file.getname () + "\" "+ line_end) sb.append (" Content-type: "+ Content_Type + line_end); Sb.append (LINE_END );d Os.write (Sb.tostring (). GetBytes ()); InputStream is = new FileInputStream (file); byte[] bytes = new Byte[1024];int len = 0;while (len = is.read (bytes))! =-1) {dos.write (bytes, 0, len);} Is.close ();d os.write (Line_end.getbytes ());d Os.flush (); Byte[] End_data = (PREFIX + boundary + PREFIX + line_end). GetBytes ();d os.write (end_data);d Os.flush ();} Dos.close (); int res = Getresponsecode ();//Return success if (res = =) {InputStream input = Conn.getinputstream (); StRingbuffer sb1 = new StringBuffer (), int ss;while ((ss = Input.read ())! =-1) {sb1.append ((char) SS);} result = Sb1.tostring (); return result;} else {}} catch (Malformedurlexception e) {log.i (tag, "Malformedurlexception error"),} catch (IOException e) {log.i (tag, "I Oexception error ");} return null;}

</pre><pre>
Article Address: http://blog.csdn.net/jmq_0000/article/details/30244297

Android Http Post File upload-----RFC1867 protocol

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.