Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> android 使用AsyncHttpClient框架上傳文件以及使用HttpURLConnection下載文件

android 使用AsyncHttpClient框架上傳文件以及使用HttpURLConnection下載文件

編輯:關於android開發

android 使用AsyncHttpClient框架上傳文件以及使用HttpURLConnection下載文件


AsyncHttpClient開源框架android-async-http還是很方便的。 AsyncHttpClient該類通常用在android應用程序中創建異步GET,

POST, PUT和DELETE HTTP請求,請求參數通過RequestParams實例創建,響應通過重寫匿名內部類 ResponseHandlerInterface的

方法處理。

1、看代碼上傳文件

 

	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");
		//批量上傳
		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() {

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable arg3) {
				Log.i("Show", "upload failed");
			}

			@Override
			public 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);  
	            // 上傳進度顯示  
	            progress.setProgress(count);  
	            Log.e("上傳 Progress>>>>>", bytesWritten + " / " + totalSize);  
	        }  
	  
	        @Override  
	        public void onRetry(int retryNo) {  
	            super.onRetry(retryNo);  
	            // 返回重試次數  
	        } 
		});
	}

 

2、刪除服務器文件代碼

 

 

	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");
		// 批量
		for (int i = 0; i < needDeleteFilesPath.size(); i++) {
			params.put("files_id", needDeleteFilesPath.get(i));
			client.setTimeout(10000);
			client.post(strDeleteFile, params, new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable arg3) {
					Log.i("Show", "delete faile");
				}

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						byte[] responseBody) {
					String  responseData = new String(responseBody);
				}
			});
		}
	}

 

3、使用使用HttpURLConnection斷點續傳下載文件

 

AsyncTask異步管理下載文件,使用HttpURLConnection斷點續傳。

 

		TaskDownFile mDownFile = new TaskDownFile();
		mDownFile.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, url_downFile,fileName, String.valueOf(nDownID));
	public class TaskDownFile extends AsyncTask {
		@Override
		protected void onPreExecute() {
		}

		@Override
		protected 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;

				// 判斷當前安裝包路徑下面是否有已經下載的文件, 如有則不下載,只需要MD5校驗即可
				String checkApkFilePath = mstrFilePath + "/" + fileName;
				File checkApkFile = new File(checkApkFilePath);

				if (checkApkFile.exists()) {
					// MD5校驗
					String md5 = md5sum(mFilePath);
					String fileTime = getFileDataTime(checkApkFile);
					// MD5校驗是否文件相同,在根據時間判斷
					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 {
						// 服務器文件最新, 刪除本地文件
						checkApkFile.delete();
					}
				}

				// 臨時安裝文件檢驗, 是否續傳文件
				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(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;
		}

		@Override
		protected void onPostExecute(Boolean isSuccess) {
			//下載後干什麼
		}
		
		@Override 
		protected void onProgressUpdate(Integer...values) {
			//進度條
			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檢驗文件

 

 

	//文件md5獲取
	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;
		}
	}

	//十六進制轉換成字符串
	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也是可以上傳、下載、刪除的。只不過下載不是很好用。

 

下載推薦使用HttpURLConnection,因為文件大的話,可以暫停下載,或者下載時候斷了,可以重新接著下載。

MD5在文件下載檢驗也是很重要,看文件有沒有丟失或者缺損。

下一章准備總結一下緩存txt數據,文件最後修改時間的比較,兩個string數據的比較。

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved