Android uses asynchttpclient framework to upload files and download files using HttpURLConnection

Source: Internet
Author: User
Tags filetime throwable

Asynchttpclient Open Source Framework Android-async-http is still very convenient. Asynchttpclient This class is typically used to create asynchronous get in an Android application,

POST, put and delete HTTP requests, request parameters created through Requestparams instances, respond by overriding anonymous inner class Responsehandlerinterface

method is processed.

1, see the Code upload file

public void UploadFile (arraylist<string> sendfilespath) {if (sendfilespath.size () = = 0) return; String struploadfile = Mstrip + mstruploadfile; Asynchttpclient client = new Asynchttpclient (); client.seturlencodingenabled (false); Requestparams params = new Requestparams ();p arams.put ("user_name", Mstruser);p arams.put ("token", mstrcheckpass); Params.put ("Dir_parent", "@sys");//bulk upload for (int i = 0; i < sendfilespath.size (); i++) {File MyFile = new file (sendfiles Path.get (i)); try {params.put (Myfile.getname (), myFile);} catch (FileNotFoundException E1) {continue;}} Client.settimeout (10000); Client.post (Struploadfile, params, new Asynchttpresponsehandler () {@Overridepublic void onfailure (int statusCode, header[] headers,byte[] responsebody, Throwable arg3) {log.i ("Show", "Upload Failed");} @Overridepublic void onsuccess (int statusCode, header[] headers,byte[] responsebody) {String responsedata = new string (); ResponseData = new String (responsebody), try {jsonobject jsonobject = new Jsonobject (responsedata); int status = Jsonobject.getint ("status"), if (status = = 1) {log.i ("Show", "Upload 1");}} catch (Exception e) {}} @Override public void onprogress (int byteswritten, int totalsize) {s              Uper.onprogress (Byteswritten, totalsize);              int count = (int) ((Byteswritten * 1.0/totalsize) * 100);              Upload Progress Display progress.setprogress (count);          LOG.E ("Upload progress>>>>>", Byteswritten + "/" + totalsize);              } @Override public void onretry (int retryno) {super.onretry (Retryno); Returns the number of Retries}});

2. Delete the server file code

public void DeleteFile (final arraylist<string> Needdeletefilespath) {if (needdeletefilespath.size () = = 0) return; String strdeletefile = Mstrip + mstrdeletefiles; Asynchttpclient client = new Asynchttpclient (); client.seturlencodingenabled (false); Requestparams params = new Requestparams ();p arams.put ("user_name", Mstruser);p arams.put ("token", mstrcheckpass); Params.put ("Dir_parent", "@sys");//bulk for (int i = 0; i < needdeletefilespath.size (); i++) {params.put ("files_id", need Deletefilespath.get (i)); Client.settimeout (10000); Client.post (Strdeletefile, params, new Asynchttpresponsehandler ( {@Overridepublic void onfailure (int statusCode, header[] headers,byte[] responsebody, Throwable arg3) {log.i ("Show", "D Elete Faile ");} @Overridepublic void onsuccess (int statusCode, header[] headers,byte[] responsebody) {String  responsedata = new String (Responsebody);}});}}

3. Use httpurlconnection breakpoint to continue downloading files

Asynctask<string, Integer, boolean> asynchronously manages the download file and uses the HttpURLConnection breakpoint to continue.

Taskdownfile mdownfile = new Taskdownfile (); Mdownfile.executeonexecutor (Asynctask.serial_executor, Url_downFile, FileName, String.valueof (Ndownid));
public class Taskdownfile extends Asynctask<string, Integer, boolean> {@Overrideprotected void OnPreExecute () {}@ overrideprotected Boolean doinbackground (String ... arg0) {string Mfilepath; String urlstring = arg0[0]; String FileName = Arg0[1];int Ndownid = Integer.parseint (arg0[2]); HttpURLConnection conn;if (Mfileinfos = = NULL | | mfileinfos.size () <= 0) return false;try {File File = new file (mstrfile Path), if (!file.exists ()) File.mkdir (), Mfilepath = Mstrfilepath + "/" + filename;//determine if there are downloaded files under the current installation package path, and if so, Only MD5 check is required for string checkapkfilepath = Mstrfilepath + "/" + fileName; File Checkapkfile = new file (Checkapkfilepath), if (Checkapkfile.exists ()) {//MD5 check string md5 = Md5sum (Mfilepath); String fileTime = Getfiledatatime (checkapkfile);//MD5 Check whether the file is the same, in accordance with the time to determine if (Md5.comparetoignorecase (Mfileinfos.get ( Ndownid). MD5) = = 0) return True;else if (Comparedatatime (Filetime,mfileinfos.get (Ndownid). Create_time) > 0) { Mnumberlist.add (Ndownid); return true;} else {//server file latest, delete local file CheckapkfilE.delete ();}} Temporary installation file verification, whether to continue the file Mfilepath = Mfilepath + ". Temp"; long havedownlength = 0; File Tempfile = new file (Mfilepath), if (Tempfile.exists ()) Havedownlength = Tempfile.length (); conn = (httpurlconnection) New URL (urlstring). OpenConnection (); if (havedownlength! = 0) Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setreadtimeout (6000); conn.setconnecttimeout, Conn.setchunkedstreamingmode (0); Conn.setrequestmethod (" GET "); Conn.connect (); int fileSize = Conn.getcontentlength (); Long countread = havedownlength;if (fileSize > 0) { InputStream stream = Conn.getinputstream (); FileOutputStream fos = new FileOutputStream (mfilepath,havedownlength > 0? true:false); int read = 0;filesize + = HaveD  Ownlength;byte buffer[] = new Byte[1024];while ((read = stream.read (buffer)) >= 0) {countread + = read;fos.write (buffer, 0, (int) read);p ublishprogress ((int) countread, fileSize);} Fos.flush (); Stream.Close (); Fos.close ();} else {fileSize = (int) havedownlength;} Conn.disconnect (); if (countreAd! = fileSize) return False;int index = Mfilepath.indexof (". temp"); if (index >= 1) {String TempFilePath = mfilepath.sub String (0, index); File RenameFile = new file (Mfilepath); File ToFile = new file (TempFilePath); Renamefile.renameto (tofile); mfilepath = Tempfilepath;return true;}} catch (IOException e) {log.i ("Show", e.tostring ()); return false;} finally {}return false;} @Overrideprotected void OnPostExecute (Boolean issuccess) {//What to do after download} @Override protected void Onprogressupdate (Integer ... values) {//progress bar if (values[0] = = null) Return;downsize = Values[0];filesize = values[1];p rogress = (int) ((values[0] * 1. 0/VALUES[1]) * 10000); Mhandler.sendemptymessage (DOWNLOAD);}}

4. MD5 Inspection Documents

File MD5 get public static string md5sum (string filename) {InputStream fis;byte[] buffer = new Byte[1024];int Numread = 0; MessageDigest md5;try {fis = new fileinputstream (filename); md5 = Messagedigest.getinstance ("MD5"); while (Numread = Fis.read (buffer)) > 0) {md5.update (buffer, 0, numread);} Fis.close (); return tohexstring (Md5.digest ());} catch (Exception e) {System.out.println ("error"); return null;}}  16 binary converted to string public static string tohexstring (byte[] b) {char hex_digits[] = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};  StringBuilder sb = new StringBuilder (B.length * 2); for (int i = 0; i < b.length; i++) {Sb.append (hex_digits[(B[i] & 0XF0) >>> 4]); Sb.append (Hex_digits[b[i] & 0x0f]);} return sb.tostring ();}

The use of asynchttpclient can also be uploaded, downloaded, deleted. But the download is not very useful.

Download recommended to use HttpURLConnection, because the file is large, you can pause the download, or the download time is broken, you can re-download.

MD5 in the file download test is also very important to see if the file is missing or defective.

The next chapter prepares to summarize the comparison of the cached TXT data, the last modified time of the file, and the comparison of two string data.








Android uses asynchttpclient framework to upload files and download files using HttpURLConnection

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.