通過Http協議下載文件、訪問接口等等

1。下載文件到指定目錄(參數url是地址,f是指定文件):

public static void downloadFile(String url, File f, Context context) {
		URL myFileUrl = null;
		try {
			MCLogUtil.i(TAG, "Image url is " + url);
			myFileUrl = new URL(url);
		} catch (Exception e) {
			return;
		}
		HttpURLConnection connection = null;
		InputStream is = null;
		FileOutputStream fo = null;
		try {
			connection = getNewHttpURLConnection(myFileUrl, context);
			connection.setDoInput(true);
			connection.connect();

			is = connection.getInputStream();
			if (f.createNewFile()) {
				fo = new FileOutputStream(f);
				byte[] buffer = new byte[256];
				int size;
				while ((size = is.read(buffer)) > 0) {
					fo.write(buffer, 0, size);
				}
			}
		} catch (MalformedURLException e) {
			MCLogUtil.i(TAG, "URL is format error");
		} catch (IOException e) {
			MCLogUtil.i(TAG, "IO error when download file");
			MCLogUtil.i(TAG, "The URL is " + url + ";the file name " + f.getName());
		} finally {
			try {
				if (fo != null) {
					fo.flush();
					fo.close();
				}
				if (is != null) {
					is.close();
				}
				if (connection != null) {
					connection.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
public static HttpURLConnection getNewHttpURLConnection(URL url, Context context) {
		HttpURLConnection connection = null;
		Cursor mCursor = null;
		try {
			connection = (HttpURLConnection) url.openConnection();
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			if (!wifiManager.isWifiEnabled()) {
				// 獲取當前正在使用的APN接入點
				Uri uri = Uri.parse("content://telephony/carriers/preferapn");
				mCursor = context.getContentResolver().query(uri, null, null, null, null);
				if (mCursor != null && mCursor.moveToFirst()) {
					// 遊標移至第一條記錄,當然也只有一條
					String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
					if (proxyStr != null && proxyStr.trim().length() > 0) {
						Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(proxyStr, 80));
						connection = (HttpURLConnection) url.openConnection(proxy);
					}
				}
			}
			return connection;
		} catch (Exception e) {
			e.printStackTrace();
			try {
				return (HttpURLConnection) url.openConnection();
			} catch (IOException e1) {
				e1.printStackTrace();
				return null;
			}
		} finally {
			if (mCursor != null) {
				mCursor.close();
			}
		}

	}

2。下載文件包含進度回調(getNewHttpURLConnection(URL url, Context context)即上述函數):

public static boolean downloadFile(Context context, String url, File f, DownProgressDelegate delegate) {
		URL fileUrl = null;
		try {
			fileUrl = new URL(url);
		} catch (Exception e) {
			return false;
		}

		HttpURLConnection connection = null;
		InputStream is = null;
		RandomAccessFile raf = null;

		try {
			f.getParentFile().mkdirs();
			f.createNewFile();
			int currentLength = (int) f.length();
			connection = HttpClientUtil.getNewHttpURLConnection(fileUrl, context);
			int length = connection.getContentLength();
			if (currentLength == length) {
				return true;
			}
			connection = HttpClientUtil.getNewHttpURLConnection(fileUrl, context);
			connection.addRequestProperty("Range", "bytes=" + currentLength + "-" + length);
			delegate.setMax(length);
			delegate.setProgress(currentLength);
			is = connection.getInputStream();
			raf = new RandomAccessFile(f, "rwd");
			raf.seek(currentLength);
			byte[] buffer = new byte[102400];
			int size;
			while ((size = is.read(buffer)) > 0) {
				raf.write(buffer, 0, size);
				currentLength = currentLength + size;
				delegate.setProgress(currentLength);
			}
			return true;
		} catch (MalformedURLException e) {
			MCLogUtil.e(TAG, e.toString());
			return false;
		} catch (Exception e) {
			MCLogUtil.e(TAG, e.toString());
			return false;
		} finally {
			try {
				if (raf != null) {
					raf.close();
					raf = null;
				}
				if (is != null) {
					is.close();
					is = null;
				}
				if (connection != null) {
					connection.disconnect();
					connection = null;
				}
			} catch (Exception e) {
				MCLogUtil.e(TAG, e.toString());
			}
		}
	}

在AsyncTask的doInBackground()中調用downloadFile()方法,並且更新UI。

@Override
	protected Boolean doInBackground(Void... params) {
		return DownloadUtils.downloadFile(context, adDownDbModel.getUrl(), file, new DownProgressDelegate() {

			public void setProgress(int progress) {
				currentProgress = progress;
				updateNotification(false, adDownDbModel);
			}

			public void setMax(int max) {
				progressMax = max;
				setProgress(0);
			}
		});
	}
private void updateNotification(boolean isBtnVisible, final AdDownDbModel adDownDbModel) {
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), MCResource.getInstance(context).getLayoutId("mc_ad_widget_notification"));
		remoteViews.setProgressBar(resource.getViewId("download_progress_bar"), progressMax, currentProgress, false);
		if (adDownDbModel.getAppName() != null) {
			remoteViews.setTextViewText(resource.getViewId("download_title_text"), adDownDbModel.getAppName());
		} else {
			remoteViews.setTextViewText(resource.getViewId("download_title_text"), getFileName(adDownDbModel.getUrl()));
		}
		.....
		notification.contentView = remoteViews;
}

3。訪問接口獲取Json:

public static String doPostRequest(String urlString, HashMap<String, String> params, Context context) {
		String result = "";
		String tempURL = urlString + "?";
		int connectionTimeout = -1;
		int socketTimeout = -1;
		if (params != null && !params.isEmpty()) {
			if (params.get(SET_CONNECTION_TIMEOUT_STR) != null) {
				connectionTimeout = Integer.parseInt(params.get(SET_CONNECTION_TIMEOUT_STR));
			}
			if (params.get(SET_SOCKET_TIMEOUT_STR) != null) {
				socketTimeout = Integer.parseInt(params.get(SET_SOCKET_TIMEOUT_STR));
			}
		}

		HttpClient client = getNewHttpClient(context, connectionTimeout, socketTimeout);
		HttpUriRequest request = null;
		HttpPost httpPost = new HttpPost(urlString);

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

			if (params != null && !params.isEmpty()) {
				for (String key : params.keySet()) {
					nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
					tempURL = tempURL + key + "=" + params.get(key) + "&";
				}
			}
			MCLogUtil.i(TAG, "tempURL = " + tempURL);
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
			request = httpPost;
			HttpResponse response = client.execute(request);
			StatusLine status = response.getStatusLine();
			int statusCode = status.getStatusCode();
			MCLogUtil.i("HttpClientUtil", "statusCode=" + statusCode);
			if (statusCode == 200) {
				result = read(response);
				MCLogUtil.i(TAG, "result = " + result);
				return result == null ? "{}" : result;
			} else {
				return BaseReturnCodeConstant.CONNECTION_FAIL;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return BaseReturnCodeConstant.CONNECTION_FAIL;
		}
	}
private static String read(HttpResponse response) throws Exception {
		String result = "";
		HttpEntity entity = response.getEntity();
		InputStream inputStream = null;
		ByteArrayOutputStream content = null;
		try {
			inputStream = entity.getContent();
			content = new ByteArrayOutputStream();

			Header header = response.getFirstHeader("Content-Encoding");
			if (header != null && header.getValue().toLowerCase().indexOf("gzip") > -1) {
				inputStream = new GZIPInputStream(inputStream);
			}

			// Read response into a buffered stream
			int readBytes = 0;
			byte[] sBuffer = new byte[512];
			while ((readBytes = inputStream.read(sBuffer)) != -1) {
				content.write(sBuffer, 0, readBytes);
			}
			// Return result from buffered stream
			result = new String(content.toByteArray());
			return result;
		} catch (IllegalStateException e) {
			throw new Exception(e);
		} catch (IOException e) {
			throw new Exception(e);
		} finally {
			if (content != null) {
				content.flush();
				content.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}
public static HttpClient getNewHttpClient(Context context, int connectionTimeout, int socketTimeout) {
		Cursor mCursor = null;
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			trustStore.load(null, null);

			HttpParams params = new BasicHttpParams();
			if (connectionTimeout > 0) {
				HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
			} else {
				HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT);
			}
			if (socketTimeout > 0) {
				HttpConnectionParams.setSoTimeout(params, socketTimeout);
			} else {
				HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT);
			}
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

			HttpClient client = new DefaultHttpClient(params);
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			if (!wifiManager.isWifiEnabled()) {
				// 獲取當前正在使用的APN接入點
				Uri uri = Uri.parse("content://telephony/carriers/preferapn");
				mCursor = context.getContentResolver().query(uri, null, null, null, null);
				if (mCursor != null && mCursor.moveToFirst()) {
					// 遊標移至第一條記錄,當然也只有一條
					String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
					if (proxyStr != null && proxyStr.trim().length() > 0) {
						HttpHost proxy = new HttpHost(proxyStr, 80);
						client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
					}
				}
			}
			return client;
		} catch (Exception e) {
			return new DefaultHttpClient();
		} finally {
			if (mCursor != null) {
				mCursor.close();
			}
		}
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章