Android_HttpURLConnection下载文件

1.读取txt.. 等文件

util类。

package com.raise.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class HttpDownloader {
	private URL url = null;

	/**
	 * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容
	 * 1.创建一个URL对象
	 * 2.通过URL对象,创建一个HttpURLConnection对象
	 * 3.得到InputStram
	 * 4.从InputStream当中读取数据
	 * @param urlStr
	 * @return
	 */
	public String download(String urlStr) {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			// 创建一个URL对象
			url = new URL(urlStr);
			// 创建一个Http连接
			HttpURLConnection urlConn = (HttpURLConnection) url
					.openConnection();
			// 使用IO流读取数据
			buffer = new BufferedReader(new InputStreamReader(urlConn
					.getInputStream()));
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	
}

Activity类

TextView testView;
	String result;
	HttpDownloader httpDownloader = new HttpDownloader();
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0x123) {
				testView.setText(result+"---->");
			}
			
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		testView = (TextView) findViewById(R.id.testText);
		new Thread(){
			public void run() {
				try {
					String urlStr = "http://10.18.33.25/mp3/nrnr.lrc";
					result = httpDownloader.download(urlStr);
					Log.i("---->",result+"----");
					handler.sendEmptyMessage(0x123);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			};
		}.start();
	}

注意,下载文件不能再mian线程中进行。


asyncTask下载文件

// 异步任务来下载音乐文件
	class DownTask extends AsyncTask<Mp3Info, Integer, String> {

		// 进度条
		ProgressDialog progressDialog;
		// 读取字节数
		int hasRead = 0;
		Context mContext;

		public DownTask(Context mContext) {
			super();
			this.mContext = mContext;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(mContext);
			// 设置标题
			progressDialog.setTitle("任务正在异步下载");
			// 设置不能被取消按钮关闭
			// progressDialog.setCancelable(false);
			// 进度条的风格
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			// 是否显示进度条的进度
			progressDialog.setIndeterminate(false);

		}

		@Override
		protected String doInBackground(Mp3Info... params) {
			Mp3Info mp3Info = params[0];
			String urlStr = LOCALHOST + "mp3/" + mp3Info.getMp3name();

			InputStream is = null;
			OutputStream os = null;
			try {
				// 下载文件,显示进度条
				// 设置内容
				progressDialog.setMessage("正在下载:"+mp3Info.getMp3name());
				// 设置进度条最大进度值
				progressDialog.setMax(Integer.parseInt(mp3Info.getMp3size()));
				URL url = new URL(urlStr);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				is = conn.getInputStream();
				// 创建文件夹和文件
				fileUtils.creatSDDir("mp3");
				File file = fileUtils
						.creatSDFile("mp3/" + mp3Info.getMp3name());
				// 写入文件
				os = new FileOutputStream(file);
				byte buffer[] = new byte[4*1024];
				int len=-1;  
				while ((len = is.read(buffer)) != -1) {
					os.write(buffer,0,len);
					hasRead += 1024;
					publishProgress(hasRead);
				}
				os.flush();
				return "下载成功";
			} catch (Exception e) {
				e.printStackTrace();
				return "下载文件出错";
			} finally {
				try {
					if (is!=null) {
						is.close();
					}
					if (os!=null) {
						os.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT)
					.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			progressDialog.show();
			progressDialog.setProgress(values[0]);
		}

	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值