Android uses the AsyncHttpClient framework to upload files and uses HttpURLConnection to download files.

Source: Internet
Author: User
Tags filetime

Android uses the AsyncHttpClient framework to upload files and uses HttpURLConnection to download files.

The android-async-http open-source framework of AsyncHttpClient is very convenient. The AsyncHttpClient class is usually used in android applications to create asynchronous GET,

POST, PUT, and delete http requests. The request parameters are created through the RequestParams instance, and the response is overwritten by

Method.

1. upload files by reading code

 

Public void uploadFile (ArrayList
 
  
SendFilesPath) {if (sendFilesPath. size () = 0) return; String strUploadFile = mstrIP + mstrUploadFile; AsyncHttpClient client = new AsyncHttpClient (); client. setURLEncodingEnabled (false); RequestParams params = new RequestParams (); params. put ("user_name", mstrUser); params. put ("token", mstrCheckPass); params. put ("dir_parent", "@ sys"); // batch upload for (int I = 0; I <sendFilesPath. size (); I ++) {File myFile = new File (sendFilesPath. 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) {super. onProgress (bytesWritten, totalSize); int count = (int) (bytesWritten * 1.0/totalSize) * 100); // the upload progress shows progress. setProgress (count); Log. e ("Upload Progress >>>>", bytesWritten + "/" + totalSize) ;}@ Override public void onRetry (int retryNo) {super. onRetry (retryNo); // number of returned retries }});}
 

 

2. Delete the Server File Code

 

 

Public void deleteFile (final ArrayList
 
  
NeedDeleteFilesPath) {if (needDeleteFilesPath. size () = 0) return; String strDeleteFile = mstrIP + mstrDeleteFiles; AsyncHttpClient client = new AsyncHttpClient (); client. setURLEncodingEnabled (false); RequestParams params = new RequestParams (); params. put ("user_name", mstrUser); params. put ("token", mstrCheckPass); params. put ("dir_parent", "@ sys"); // batch for (int I = 0; I <needDeleteFilesPath. size (); I ++) {params. put ("files_id", needDeleteFilesPath. 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", "delete faile") ;}@ Overridepublic void onSuccess (int statusCode, Header [] headers, byte [] responseBody) {String responseData = new String (responseBody );}});}}
 

 

3. Use HttpURLConnection to resume object download

 

AsyncTask Use HttpURLConnection to manage download files asynchronously.

 

TaskDownFile mDownFile = new TaskDownFile();mDownFile.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, url_downFile,fileName, String.valueOf(nDownID));
Public class TaskDownFile extends AsyncTask
 
  
{@ 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 (mstrFilePath); if (! File. exists () file. mkdir (); mFilePath = mstrFilePath + "/" + fileName; // you can check whether any downloaded file exists in the current installation package path, 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, determine if (md5.compareToIgnoreCase (mFileInfos. get (nDownI D ). 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 check, whether to resume the file mFilePath = mFilePath + ". temp "; long haveDownLength = 0; File tempFile = new File (mFilePath); if (tempFile. exists () haveDownLength = tempFile. length (); conn = (HttpURLConnection) new URL (urlStrin G). openConnection (); if (haveDownLength! = 0) conn. setRequestProperty ("Connection", "Keep-Alive"); conn. setreadtimeouts (6000); conn. setConnectTimeout (3000); 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 + = haveDownLength; byte buffer [] = new byte [1024]; while (read = stream. read (buffer)> = 0) {countRead + = read; fos. write (buffer, 0, (int) read); publishProgress (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. 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]; progress = (int) (values [0] * 1.0/values [1]) * 10000); mHandler. sendEmptyMessage (DOWNLOAD );}}
 

 

4. MD5 check file

 

 

// Obtain the public static String md5sum (String filename) {InputStream FCM; byte [] buffer = new byte [1024]; int numRead = 0; MessageDigest md5; try {FCM = new FileInputStream (filename); md5 = MessageDigest. getInstance ("MD5"); while (numRead = Fi. read (buffer)> 0) {md5.update (buffer, 0, numRead);} FD. close (); return toHexString (md5.digest ();} catch (Exception e) {System. out. println ("error"); return null ;}// convert the hexadecimal String to 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 ();}

AsyncHttpClient can also be uploaded, downloaded, and deleted. Download is not very useful.

 

We recommend that you use HttpURLConnection for downloading. If the file size is large, you can pause the download or the download is interrupted. You can download the file again.

MD5 is also very important in the file download test. Check whether the file is missing or missing.

The next chapter will summarize the comparison of the cached txt data, the last modification time of the file, and the comparison of the two string data.

 

 

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.