使用HttpURLConnection(实现单线程多线程下载)
2015-09-12 08:57
483 查看
HttpURLConnection继承URLConnection因此也可向指定网站发送POST,GET请求
【2】获取指定URL对象指向的资源的大小,getContentLength()方法实现;
【3】在本地磁盘创建与资源大小相当的文件
【4】计算每个线程应该下载资源的分配(从那个字节开始,到哪个字节结束)
【5】依次创建启动多个线程下载
单线程下载
class SingleDownloadTask extends AsyncTask<String, Integer, String> { @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); // int count= Integer.parseInt(values[1]*100.0/values[0]); mProgressBar.setProgress((int) (values[0] * 100.0 / values[1])); } @Override protected String doInBackground(String... params) { try { URL url = new URL("http://192.168.0.30:8080/MyWebTest/music/aa.mp3"); URLConnection connection = url.openConnection(); int length = connection.getContentLength(); //publishProgress(length); InputStream is = connection.getInputStream(); File file = new File(Environment.getExternalStorageDirectory(), "aa.mp3"); if (!file.exists()) { file.createNewFile(); } FileOutputStream os = new FileOutputStream(file); byte[] array = new byte[1024]; int sum = 0; int index = is.read(array); while (index != -1) { os.write(array, 0, index); sum += index; publishProgress(sum, length); index = is.read(array); } os.flush(); os.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } }
多线程下载步骤
【1】创建URL对象【2】获取指定URL对象指向的资源的大小,getContentLength()方法实现;
【3】在本地磁盘创建与资源大小相当的文件
【4】计算每个线程应该下载资源的分配(从那个字节开始,到哪个字节结束)
【5】依次创建启动多个线程下载
private void MultiThreadDownload() { new Thread() { @Override public void run() { String urlPath = "http://192.168.0.30:8080/MyWebTest/music/aa.mp3"; try { URL url = new URL(urlPath); URLConnection connection = url.openConnection(); length = connection.getContentLength(); File file = new File(Environment.getExternalStorageDirectory(), "cc.mp3"); if (!file.exists()) { file.createNewFile(); } MultiThread[] threads = new MultiThread[5]; for (int i = 0; i < 5; i++) { MultiThread thread = null; if (i == 4) { thread = new MultiThread(length / 5 * 4, length, urlPath, file.getAbsolutePath()); } else { thread = new MultiThread(length / 5 * i, length / 5 * (i + 1)-1, urlPath, file.getAbsolutePath()); } thread.start(); threads[i] = thread; } boolean isFinish = true; while (isFinish) { int sum = 0; for (MultiThread thread : threads) { sum += thread.getSum(); } Message msg = handler.obtainMessage(); msg.what = 0x23; msg.arg1 = sum; handler.sendMessage(msg); if (sum + 10 >= length) { isFinish = false; } Thread.sleep(1000); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); }
public class MultiThread extends Thread{ public MultiThread(long start, long end, String url, String filePath) { this.start = start; this.end = end; this.urlPath = url; this.filePath = filePath; } private int sum=0; private long start; private long end; private String urlPath; private String filePath; public int getSum() { return sum; } @Override public void run() { try { URL url = new URL(urlPath); URLConnection connection=url.openConnection(); connection.setAllowUserInteraction(true); connection.setRequestProperty("Range","byte="+start+"-"+end); InputStream is=connection.getInputStream(); byte[] array=new byte[1024]; is.read(array); File file=new File(filePath); RandomAccessFile randomAccessFile=new RandomAccessFile(file,"rw"); randomAccessFile.seek(start); int index=is.read(array); while(index!=-1){ randomAccessFile.write(array,0,index); sum+=index; index=is.read(array); } randomAccessFile.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
public class DownloadActivity extends Activity implements View.OnClickListener {
private Button mButtonSingle;
private Button mButtonMilti;
private ProgressBar mProgressBar;
private int length;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x23:
mProgressBar.setProgress(msg.arg1 * 100 / length);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
mButtonSingle = (Button) findViewById(R.id.button_download_single);
mButtonMilti = (Button) findViewById(R.id.button_download_milti);
mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
mButtonMilti.setOnClickListener(this);
mButtonSingle.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_download_single:
SingleDownloadTask task = new SingleDownloadTask();
task.execute();
break;
case R.id.button_download_milti:
MultiThreadDownload();
break;
default:
break;
}
}
private void MultiThreadDownload() { new Thread() { @Override public void run() { String urlPath = "http://192.168.0.30:8080/MyWebTest/music/aa.mp3"; try { URL url = new URL(urlPath); URLConnection connection = url.openConnection(); length = connection.getContentLength(); File file = new File(Environment.getExternalStorageDirectory(), "cc.mp3"); if (!file.exists()) { file.createNewFile(); } MultiThread[] threads = new MultiThread[5]; for (int i = 0; i < 5; i++) { MultiThread thread = null; if (i == 4) { thread = new MultiThread(length / 5 * 4, length, urlPath, file.getAbsolutePath()); } else { thread = new MultiThread(length / 5 * i, length / 5 * (i + 1)-1, urlPath, file.getAbsolutePath()); } thread.start(); threads[i] = thread; } boolean isFinish = true; while (isFinish) { int sum = 0; for (MultiThread thread : threads) { sum += thread.getSum(); } Message msg = handler.obtainMessage(); msg.what = 0x23; msg.arg1 = sum; handler.sendMessage(msg); if (sum + 10 >= length) { isFinish = false; } Thread.sleep(1000); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); }
class SingleDownloadTask extends AsyncTask<String, Integer, String> { @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); // int count= Integer.parseInt(values[1]*100.0/values[0]); mProgressBar.setProgress((int) (values[0] * 100.0 / values[1])); } @Override protected String doInBackground(String... params) { try { URL url = new URL("http://192.168.0.30:8080/MyWebTest/music/aa.mp3"); URLConnection connection = url.openConnection(); int length = connection.getContentLength(); //publishProgress(length); InputStream is = connection.getInputStream(); File file = new File(Environment.getExternalStorageDirectory(), "aa.mp3"); if (!file.exists()) { file.createNewFile(); } FileOutputStream os = new FileOutputStream(file); byte[] array = new byte[1024]; int sum = 0; int index = is.read(array); while (index != -1) { os.write(array, 0, index); sum += index; publishProgress(sum, length); index = is.read(array); } os.flush(); os.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } }
}
相关文章推荐
- Linux tcpdump命令详解
- C++ 用libcurl库进行http通讯网络编程
- 网络配置
- linux网络设置(有网卡别名介绍)
- thttpd增加gzip压缩响应报文体功能,以减少传输数据量
- 卷积神经网络的一些细节
- 利用iftop查看网络带宽使用情况
- Ubuntu实现网络链接设置
- 旧手机利用 第二弹 ——网络摄像头
- 【CCF】无线网络
- JavaWeb——HTTP协议头部分析
- Socket/TCP粘包、多包和少包, 断包
- 黑马程序员----网络编程
- 黑马程序员——TCP协议传输(下)
- HTTPS那些事(一)HTTPS原理
- Linux基本网络知识
- Linux内核工程导论——网络:内核特性
- Linux内核工程导论——网络:Socket
- 使用dup2重定向了标准输出后,使用什么方法恢复对终端的输出?? http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=359433&page=
- 黑马程序员——TCP协议传输(上)