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

Source: Internet
Author: User
Tags http post rfc


RFC1867 Protocol Introduction
RFC1867 protocol is mainly on the basis of the HTTP protocol to add the file attribute to the input tag, while defining the form must be the method of POST, 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 The media content complies with the 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 (this refers to HTML, of course, some other applications can also   use the form), there are a series of fields provided to the user to fill in, each field has its own name. In a certain form, each name is unique.  
       multipart/form-data consists of multiple parts, each with a content-disposition header, with a value of "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. If the field name contains non-ASCII characters, it should also be encoded according to the method specified in RFC 1522.  
        for all multi-part MIME types, each section has an optional Content-type, and the default value is Text/plain. If the content of the file is returned by the form fill upload, the input file is defined as Application/octet-stream, or, if you know what type it is, it is defined as the appropriate media type. If a form returns multiple files, they are returned as a combination of multipart/mixed in Multipart/form-data.  
If the transferred content does not conform to the default encoding, that part will be encoded, plus the header of "content-transfer-encoding". &NBSP;


Implementation of the Android post upload file

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


/** * * @param urlpath * @param params * Map parameter < parameter name, parameter value > * @param fileparams * Map File type parameter Number < parameter name, file path > * */public string Postfile (String URLPath, map<string, object> params,map<string, String&gt ;  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");//Open 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); Gets the output stream DataOutputStream dos = new DataOutputStream (Connection.getoutputstream ()); StringBuffer SB = null; String result = ""; String paramstr;//Send non-file parameter if (mparams! = null && mparams.size () > 0) {iterator<string> it = Mparams.keyset (). 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 parameter, 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 ();} <span style= "White-space:pre" ></span>//set the border mark, set content-disposition header 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 ()) byte[] End_data = (PREFIX + boundary + PREFIX + line_end). GetBytes (); Dos.write (End_data);d Os.flush ();}} Dos.close (); int res = Getresponsecode ();//Return success if (res = = 2XX) {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, "IOException error"); } return null; }


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.