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

Source: Internet
Author: User
Tags filetime

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

POST, put, and delete HTTP requests. The request parameters are created from the Requestparams instance. The response is overridden by overriding the 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;//infers if there are any downloaded files below the current installation package path, Only need MD5 check can be 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. On the basis time infer 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 is up to date. Delete local file CheckaPkfile.delete ();}} Temporarily install the file check, 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 = Mfilepat H.substring (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 is also able to upload, download, delete.

Just downloading is not very useful.

Download recommended use of HttpURLConnection. You can pause the download because the file is large. Or the download time is broken. can then download again.

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 cached TXT data. A comparison of the time the file was last modified. A 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.