Uploading files using volley

Source: Internet
Author: User
Tags getmessage

Use the browser to upload files, and then through the Wireshark capture packet analysis, found that the data sent is probably the same way.

MIME Multipart Media Encapsulation, Type:multipart/form-data, boundary: "----WEBKITFORMBOUNDARY1UBMMKIKN58CIVN4" [TYP         E:multipart/form-data] First boundary:------webkitformboundary1ubmmkikn58civn4\r\n encapsulated Multipart part: Content-disposition:form-data; Name= "name" \r\n\r\n Data (bytes) boundary: \ r \ n------webkitformboundary1ubmmkikn58civn4\r\n encapsulated M Ultipart part: (image/png) Content-disposition:form-data; Name= "photo[]"; Filename= "screenshot (2). png \ r \ n content-type:image/png\r\n\r\n portable Network Graphics boundary: \r\ n------webkitformboundary1ubmmkikn58civn4\r\n Encapsulated multipart part: (image/png) boundary: \ r \------WEBKITFO rmboundary1ubmmkikn58civn4\r\n encapsulated multipart part: (image/png) boundary: \ r \ n------webkitformboundary1ubmm     kikn58civn4\r\n encapsulated multipart part: (image/png) boundary: \ r \ n------webkitformboundary1ubmmkikn58civn4\r\n Encapsulated multipart Part: (image/png) last boundary: \ r \ n------webkitformboundary1ubmmkikn58civn4--\r\n 

The

First comes from defining a httpentity,

Package Cc.dewdrop.volleydemo.utils;import Com.android.volley.volleylog;import Org.apache.http.header;import Org.apache.http.httpentity;import Org.apache.http.message.basicheader;import Java.io.ByteArrayInputStream;import Java.io.bytearrayoutputstream;import Java.io.closeable;import Java.io.file;import Java.io.FileInputStream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream; Import javax.activation.mimetypesfiletypemap;/** * Created by Tingkuo on 12/1/2015. */public class Fileuploadentity implements httpentity {private static final String TAG = FileUploadEntity.class.getSim    Plename ();    Private static final String boundary = "__file_upload_entity__";    Private Bytearrayoutputstream Moutputstream;        Public fileuploadentity () {moutputstream = new Bytearrayoutputstream ();        try {writefirstboundary ();        } catch (IOException e) {e.printstacktrace (); }} Private VOID Writefirstboundary () throws IOException {volleylog.e ("writefirstboundary");        Moutputstream.write ("--" + boundary + "\ r \ n"). GetBytes ()); Moutputstream.write ("Content-disposition:form-data;        Name=\ "" + "name" + "\" \r\n\r\n "). GetBytes ());        Moutputstream.write ("content-transfer-encoding:binary\n\n". GetBytes ());    Moutputstream.flush ();        } private void Writelastboundary () throws IOException {volleylog.e ("writelastboundary");    Moutputstream.write (("\r\n--" + boundary + "--\r\n"). GetBytes ());        The public void AddFile (final String key, final file file) {volleylog.e ("AddFile");        InputStream inputstream = null;            try {moutputstream.write ("\r\n--" + boundary + "\ r \ n"). GetBytes ());            StringBuilder stringbuildercontentdisposition = new StringBuilder ();            Stringbuildercontentdisposition.append ("content-disposition:");       Stringbuildercontentdisposition.append ("form-data;");     Stringbuildercontentdisposition.append ("name=\" "+ key +" \ ";            ");            Stringbuildercontentdisposition.append ("filename=\" "+ file.getname () +" \ "\" \ \ \ \ \ ");            Moutputstream.write (Stringbuildercontentdisposition.tostring (). GetBytes ());            StringBuilder Stringbuildercontenttype = new StringBuilder ();            Stringbuildercontenttype.append ("Content-type:");            Stringbuildercontenttype.append (New Mimetypesfiletypemap (). getContentType (file). toString ());            Stringbuildercontenttype.append ("\r\n\r\n");            Moutputstream.write (Stringbuildercontenttype.tostring (). GetBytes ());            InputStream = new FileInputStream (file);            Final byte[] buffer = new byte[1024];            int len = 0;                while (len = inputstream.read (buffer))! =-1) {VOLLEYLOG.E ("Len-to-%s", string.valueof (len));            Moutputstream.write (buffer, 0, Len); } volleylog.e ("===last====len-and-%s", String. ValueOf (len));        Moutputstream.flush ();        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();        } finally {closesilently (inputstream);                }} private void closesilently (closeable closeable) {try {if (closeable! = null) {            Closeable.close ();        }} catch (Final IOException e) {e.printstacktrace ();    }} @Override public boolean isrepeatable () {return false;    } @Override public Boolean ischunked () {return false;    } @Override public Long getcontentlength () {return Moutputstream.tobytearray (). length; } @Override Public Header getContentType () {return new Basicheader ("Content-type", "multipart/form-data;    boundary= "+ boundary);    } @Override Public Header getcontentencoding () {return null; } @Override Public InputstrEAM getcontent () throws IOException, unsupportedoperationexception {return new Bytearrayinputstream (Moutputstream.    Tobytearray ());        } @Override public void WriteTo (OutputStream outputstream) throws IOException {writelastboundary ();    Outputstream.write (Moutputstream.tobytearray ());    } @Override public Boolean isstreaming () {return false; } @Override public void Consumecontent () throws IOException {}}

Now to explain, first this is to support multi-file upload, the data format includes four parts, Content-type,first boundary, file binary data [], and last boundary. You can have multiple files, insert them using the AddFile method, and you need a delimiter boundary between the files. Each file needs to have content-disposition and Content-type

Then customize a request and use different construction methods as needed

Package Cc.dewdrop.volleydemo.utils;import Com.android.volley.authfailureerror;import Com.android.volley.networkresponse;import Com.android.volley.request;import Com.android.volley.response;import Com.android.volley.response.listener;import Com.android.volley.response.errorlistener;import Com.android.volley.toolbox.httpheaderparser;import Java.io.bytearrayoutputstream;import java.io.IOException; Import Java.io.unsupportedencodingexception;import java.util.hashmap;import java.util.map;/** * Created by Tingkuo on 12/2/2015.    */public class Fileuploadrequest extends request<string> {private final listener<string> mlistener;    Private fileuploadentity mfileuploadentity = new fileuploadentity ();    Private map<string, string> mheaders = new hashmap<> ();    Public fileuploadrequest (String URL, listener<string> Listener) {This (URL, Listener, null); } public fileuploadrequest (String URL, listener<string> Listener, Errorlistener Errorlistener{This (method.post, URL, Listener, errorlistener);        } public fileuploadrequest (int method, String URL, listener<string> Listener, Errorlistener errorlistener) {        Super (method, URL, errorlistener);    This.mlistener = listener;    } public fileuploadentity getfileuploadentity () {return mfileuploadentity;    } @Override Public String Getbodycontenttype () {return Mfileuploadentity.getcontenttype (). GetValue ();    } public void AddHeader (string key, String value) {Mheaders.put (key, value);    } @Override public map<string, String> getheaders () throws Authfailureerror {return mheaders; } @Override Public byte[] GetBody () throws Authfailureerror {Bytearrayoutputstream outputstream = new Bytear        Rayoutputstream ();        try {mfileuploadentity.writeto (outputstream);        } catch (IOException e) {e.printstacktrace ();   } return Outputstream.tobytearray (); } @Override protected response<string> parsenetworkresponse (Networkresponse Response) {String parsed        = "";        try {parsed = new String (Response.data, Httpheaderparser.parsecharset (response.headers));        } catch (Unsupportedencodingexception e) {parsed = new String (response.data);    } return Response.success (parsed, httpheaderparser.parsecacheheaders (Response)); } @Override protected void Deliverresponse (String response) {if (Mlistener! = null) {MLISTENER.O        Nresponse (response); }    }}

The code is put in volley other types of request to write, nothing to say.

The last is how to call

    private void Simpleuploadfile () {File File = new file (Environment.getexternalstoragedirectory (). GetPath () + "/        Upload.png ");                Fileuploadrequest = new Fileuploadrequest (Request.Method.POST, Urllist.get (2), New Response.listener<string> () {@Override public void Onresponse (String r                        Esponse) {textviewinfo.settext ("Post succeed:\n" + response.replace ("<br>", "\ n"));                        LOG.E (TAG, response);                    Dialog.dismiss (); }}, new Response.errorlistener () {@Override public V OID Onerrorresponse (volleyerror error) {textviewinfo.settext ("Post failed:\n" + error.getmessage ()                        );                        LOG.E (TAG, Error.getmessage ());                    Dialog.dismiss ();    }                }        );    Fileuploadrequest.addheader ("User-agent", "Android 5.1.1");        Fileuploadentity fileuploadentity = fileuploadrequest.getfileuploadentity ();        Fileuploadentity.addfile ("file[]", file);        Fileuploadentity.addfile ("file[]", file);        Fileuploadentity.addfile ("file[]", file);        Fileuploadentity.addfile ("file[]", file);        Fileuploadentity.addfile ("file[]", file);        Requestqueue.add (fileuploadrequest);    Dialog.show (); }

Instantiate a new request object, pass in the Method,url, then get the entity through the request object, pass the AddFile () method to the file to be uploaded, and finally add the Requestqueue, Use the same method as other types of request.

Note:

You need to add the following dependencies:

    Compile ' org.apache.httpcomponents:httpcore:4.4.4 '    compile ' org.apache.httpcomponents:httpmime:4.5.1 '    Compile files (' Libs/volley.jar ')    compile files (' Libs/activation.jar ')

  

Uploading files using volley

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.