android网络下载及保存

protected void downXMLFile(final String url,Handler mHandler) {

		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				client.getParams().setParameter(
						CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
				client.getParams().setParameter(
						CoreConnectionPNames.SO_TIMEOUT, 10000);
				try {
					response = client.execute(get);
					if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
						HttpEntity entity = response.getEntity();
						long length = entity.getContentLength();

						InputStream is = entity.getContent();
						FileOutputStream fileOutputStream = null;
						if (is == null) {
							throw new RuntimeException("isStream is null");
						}
						String filename = HiStoreFileMutileDownLoad
								.getFilenName(url);
						File file = new File(XMLPath, filename);
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int percent = 0;
						int prepercent = -1;
						writeSize = 0;
						do {
							ch = is.read(buf);
							if (ch <= 0)
								break;
							fileOutputStream.write(buf, 0, ch);
							writeSize += ch;
							percent = (int) ((writeSize * 100) / length);
//							Log.i(TAG, "ch =" + ch + " writeSize="
//									+ writeSize + " percent=" + percent
//									+ " prepercent=" + prepercent);

						} while (true);
						is.close();
						fileOutputStream.close();
						if (mhandler != null&&url.equals(xmlfileUrl[0])) {//下载完成后通知更新界面,解决有时第一开启动histore时由于下载未完成而获取不到数据的问题
							mhandler.sendEmptyMessage(0x004);
						}
					} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
						Log.e(TAG, "update packaget not found!!! ");
						IshostOK++;
						if (IshostOK >= 3) {
							IshostOK = 0;
							if (mhandler != null) {
								mhandler.sendEmptyMessage(0x003);
							}
						}
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					// 下载xml,如果失败则可以推出服务器不稳定,从而用handler发出信号给showdialog
					IshostOK++;
					if (IshostOK >= 3) {
						IshostOK = 0;
						if (mhandler != null) {
							mhandler.sendEmptyMessage(0x003);
						}
					}
					Log.v(TAG, "update packaget not found!!! IshostOK = "
							+ IshostOK);
					e.printStackTrace();
				}
			}
		}.start();
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值