android 使用AsyncHttpClient框架上传文件以及使用HttpURLConnection下载文件

Posted yfceshi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android 使用AsyncHttpClient框架上传文件以及使用HttpURLConnection下载文件相关的知识,希望对你有一定的参考价值。

AsyncHttpClient开源框架android-async-http还是非常方便的。 AsyncHttpClient该类通经常使用在android应用程序中创建异步GET,

POST, PUT和DELETE HTTP请求。请求參数通过RequestParams实例创建。响应通过重写匿名内部类 ResponseHandlerInterface的

方法处理。

1、看代码上传文件

	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();
		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、删除server文件代码

	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();
		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<String, Integer, Boolean>异步管理下载文件,使用HttpURLConnection断点续传。

		TaskDownFile mDownFile = new TaskDownFile();
		mDownFile.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, url_downFile,fileName, String.valueOf(nDownID));
	public class TaskDownFile extends AsyncTask<String, Integer, Boolean> {
		@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 {
						// server文件最新。 删除本地文件
						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数据的比較。






















以上是关于android 使用AsyncHttpClient框架上传文件以及使用HttpURLConnection下载文件的主要内容,如果未能解决你的问题,请参考以下文章

android在service中使用AsyncHttpClient加载网络资源

android AsyncHttpClient 的作用好处?

如何使用 AsyncHttpClient 发送 JSON 正文?

AsyncHttpClient 实战总结及思考

as使用 AsyncHttpClient 报错的问题,是因为版本新了,而android6.9 就把HttpClient给删除了

Android之网络编程