Android uses httpurlconnection to implement file upload with parameters

Source: Internet
Author: User
Tags response code

File upload is a common function, however, most of the Android Internet File upload use httpclient, and need to add a httpmine-jar, in fact, HttpURLConnection can also implement file upload, but it has a disadvantage on the mobile side, Just can't upload large files, so this time to say the way, can only upload some smaller files.

File upload, and with some parameters, this requires us to understand how the HTTP request is constructed, that is, its format.

HttpURLConnection need us to construct our own request header, that is, we want to stitch up a correct and complete request.

Let's look at a typical example

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= "param1" content-type:text/plain; Charset=utf-8content-transfer-encoding:8bit888--ocqxmf6-jxtxomdhmog5w5ey9mgrstbpcontent-disposition:form-data; Name= "param2" content-type:text/plain; Charset=utf-8content-transfer-encoding:8bit "Nihao"--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--

In the example above, we first look at
Post/api/feed/http/1.1accept-encoding:gzipcontent-length:225873content-type:multipart/form-data; Boundary=ocqxmf6-jxtxomdhmog5w5ey9mgrstbphost:www.myhost.comconnection:keep-alive
The first line: For post, the sub-path to request is/api/feed/, for example our server address is www.myhost.com, then our full path to this request is www.myhost.com/api/feed/, Finally, the HTTP protocol version number 1.1 is explained.

Second line: Data compression method

Third line: Data length

Line four: Multipart/form-data; refers to the uploaded data type, here refers to the file form. Boundary is a delimiter that we must specify, separated by this delimiter between different parameters. And OCQXMF6-JXTXOMDHMOG5W5EY9MGRSTBP is the specific delimiter, which we can generate randomly.

Line five: Host address

Line Six: Persistent connection,keep-alive function avoids establishing or re-establishing a connection

Line seventh: line break, this line break is necessary, we use \ r \ n for line break


And then there's the parameter content part, let's see.

--ocqxmf6-jxtxomdhmog5w5ey9mgrstbpcontent-disposition:form-data; Name= "param1" content-type:text/plain; charset=utf-8content-transfer-encoding:8bit888
We think of the above as a whole.

First line: I want to first declare the beginning of a parameter with a delimiter. Note that the separator is preceded by two horizontal "--", this also must be added!

The second line: Name= "param1", in fact param1 is the key value of the parameters passed, for example, in the Get method, we write http://www.baidu.com?param1=888

The third line: the same content format, but this time is to specify the text, so it is text/plain; In addition, the encoding method is specified charset=utf-8

Line Fourth: describes the transport form of the entity object (entities) that accompanies the message request and Response (response) . Simple Text data we set to 8bit, file parameters we set to binary on the line

Line five: line, this is a must!

Line six: parameter values, such as http://www.baidu.com?param1=888, are 888


OK, let's take a look at the next parameter.

--ocqxmf6-jxtxomdhmog5w5ey9mgrstbpcontent-disposition:form-data; Name= "param2" content-type:text/plain; Charset=utf-8content-transfer-encoding:8bit "Nihao"

And then the next parameter is the file.

Although the specified content is different, the format is the same

--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--

OK, we carefully look at the above format, can not make a mistake, because the format is not, can not upload.


Next, we look directly at the one I wrote with the parameter file Upload Tool class

/** * Created by Kaiyi.cky on 2015/8/16.    */public class Fileuploader {private static final String TAG = "UploadFile"; private static final int time_out = 10*10000000; Timeout time private static final String CHARSET = "Utf-8";    Set the encoding private static final String PREFIX = "--";    private static final String line_end = "\ r \ n"; public static void upload (String host,file file,map<string,string> Params,fileuploadlistener listener) {Strin G boundary = Uuid.randomuuid (). toString ();        The boundary identifier randomly generates a String PREFIX = "--", Line_end = "\ r \ n"; String content_type = "Multipart/form-data";            Content type try {URL url = new URL (host);            HttpURLConnection conn = (httpurlconnection) url.openconnection ();            Conn.setreadtimeout (time_out);            Conn.setconnecttimeout (time_out); Conn.setrequestmethod ("POST"); Request Mode Conn.setrequestproperty ("Charset", Charset);//Set Encoding Conn.setrequestproperty ("Connection", "Kee P-alive");            Conn.setrequestproperty ("Content-type", Content_Type + "; boundary=" + boundary); Conn.setdoinput (TRUE); Allow input stream Conn.setdooutput (true); Allow output stream conn.setusecaches (false); Cache if (file!=null) {/** * is not allowed when the file is not empty, the file is packaged and uploaded */OutputStream Outputsteam=con                N.getoutputstream ();                DataOutputStream dos = new DataOutputStream (outputsteam);                StringBuffer sb = new StringBuffer ();                Sb.append (Line_end);                                                if (params!=null) {//Based on format, start stitching text parameter for (map.entry<string,string> Entry:params.entrySet ()) { Sb.append (PREFIX). Append (Boundary). Append (line_end);//delimiter sb. Append ("Content-disposition:form-data;                        Name=\ "" + entry.getkey () + "\" "+ line_end); Sb.append ("Content-type:text/plain;                        Charset= "+ charset + line_end); Sb.append ("ConteNt-transfer-encoding:8bit "+ line_end);                        Sb.append (Line_end);                        Sb.append (Entry.getvalue ());                    Sb.append (line_end);//Change line! }} sb.append (PREFIX);//Start Stitching file Parameters Sb.append (boundary);                Sb.append (Line_end); /** * Here the key NOTE: * Name inside the value for the server side need key only this key can get the corresponding file * filename is the name of the file, including after For example: Abc.png */Sb.append ("Content-disposition:form-data; Name=\ "img\";                Filename=\ "" +file.getname () + "\" "+line_end); Sb.append ("Content-type:application/octet-stream;                Charset= "+charset+line_end);                Sb.append (Line_end);                Write file Data dos.write (Sb.tostring (). GetBytes ());                InputStream is = new FileInputStream (file);                byte[] bytes = new byte[1024];                Long totalbytes = File.length (); Long curbytes = 0;                LOG.I ("Cky", "total=" +totalbytes);                int len = 0;                    while ((Len=is.read (bytes))!=-1) {curbytes + = Len;                    Dos.write (bytes, 0, Len);                Listener.onprogress (curbytes,1.0d*curbytes/totalbytes);                } is.close ();                Dos.write (Line_end.getbytes ()); \ \ There must be a newline byte[] End_data = (prefix+boundary+prefix+line_end). GetBytes ();                Dos.write (End_data);                Dos.flush (); /** * Get response Code 200 = Success * When the response is successful, get the stream of the response */int code = Conn.getres                Ponsecode ();                Sb.setlength (0);                BufferedReader br = new BufferedReader (New InputStreamReader (Conn.getinputstream ()));                String Line;                while ((Line=br.readline ())!=null) {sb.append (line); } listener.onfinish (Code,sb.tostring (), Conn.Getheaderfields ());        }} catch (Malformedurlexception e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();        }} public interface fileuploadlistener{public void onprogress (long pro,double precent);    public void onfinish (int code,string res,map<string,list<string>> headers); }}

The way to use this is:

public class Mainactivity extends fragmentactivity {File sddir;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Sddir = null;   Boolean sdcardexist = Environment.getexternalstoragestate (). Equals (environment.media_mounted);        Determine if the SD card exists if (sdcardexist) {sddir = Environment.getexternalstoragedirectory ();//Get with Directory}        Final hashmap<string,string> map = new hashmap<string,string> ();        Map.put ("AA", "BB"); New Thread () {@Override public void run () {fileuploader.upload ("Upload address", New File (Sddi  R.getpath () + "/filename"), map, new Fileuploader.fileuploadlistener () {@Override public                    void OnProgress (Long pro, double precent) {log.i ("cky", precent+ "");         } @Override           public void onfinish (int code, String res, map<string, list<string>> headers) {                    LOG.I ("Cky", res);            }                });            }}.start (); }   }


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android uses httpurlconnection to implement file upload with parameters

Related Article

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.