android HttpURLConnection实现多线程下载

来源:互联网 发布:粉色水晶 知乎 编辑:程序博客网 时间:2024/05/02 22:21

使用HttpURLConnection实现多线程下载

分类: Android 1809人阅读 评论(2)收藏 举报
AndroidHttpURLConnection多线程下载

HttpURLConnection继承了URLConnection,因此也可用于向指定网站发送GET请求、POST请求,而且它在URLConnection基础上提供了如下便捷方法:

实现多线程下载的步骤:

下面用一个示例来示范使用HttpURLConnection实现多线程下载。此代码来源疯狂讲义一书,该代码主要思路:在Activity中点击按钮,调用DownUtil的download()方法,在download()中启动四个线程去下载资源,每个线程负责下载自己的那部分资源,代码如下:

Activity:

[java] view plaincopyprint?
  1. package com.home.activity;  
  2.   
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5.   
  6. import android.app.Activity;  
  7. import android.os.Bundle;  
  8. import android.os.Handler;  
  9. import android.os.Message;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.EditText;  
  14. import android.widget.ProgressBar;  
  15.   
  16. import com.home.multithreaddown.R;  
  17. import com.home.util.DownUtil;  
  18.   
  19. public class MultiThreadDownActivity extends Activity {  
  20.     private EditText urlText;  
  21.     private EditText targetText;  
  22.     private Button downBtn;  
  23.     private ProgressBar bar;  
  24.     private DownUtil downUtil;  
  25.     private int mDownStatus;  
  26.     private Handler handler;  
  27.   
  28.     @Override  
  29.     protected void onCreate(Bundle savedInstanceState) {  
  30.         super.onCreate(savedInstanceState);  
  31.         setContentView(R.layout.main);  
  32.         // 获取界面中控件  
  33.         targetText = (EditText) findViewById(R.id.main_et_name);  
  34.         urlText = (EditText) findViewById(R.id.main_et_url);  
  35.         downBtn = (Button) findViewById(R.id.main_btn_download);  
  36.         bar = (ProgressBar) findViewById(R.id.main_progressBar);  
  37.         // 创建一个Handler对象  
  38.         handler = new Handler() {  
  39.             public void handleMessage(Message msg) {  
  40.                 if (msg.what == 0x123) {  
  41.                     bar.setProgress(mDownStatus);  
  42.                 }  
  43.             }  
  44.         };  
  45.         downBtn.setOnClickListener(new OnClickListener() {  
  46.   
  47.             @Override  
  48.             public void onClick(View v) {  
  49.                 // 初始化DownUtil对象  
  50.                 downUtil = new DownUtil(urlText.getText().toString(),  
  51.                         targetText.getText().toString(), 4);  
  52.                 try {  
  53.                     // 开始下载  
  54.                     downUtil.download();  
  55.                 } catch (Exception e) {  
  56.                     e.printStackTrace();  
  57.                 }  
  58.                 // 定义每秒调度获取一次系统的完成进度  
  59.                 final Timer timer = new Timer();  
  60.                 timer.schedule(new TimerTask() {  
  61.                     public void run() {  
  62.                         // 获取下载任务的完成比率  
  63.                         double completeRate = downUtil.getCompleteRate();  
  64.                         mDownStatus = (int) (completeRate * 100);  
  65.                         // 发送消息通知界面更新进度条  
  66.                         handler.sendEmptyMessage(0x123);  
  67.                         // 下载完成后取消任务调度  
  68.                         if (mDownStatus >= 100) {  
  69.                             timer.cancel();  
  70.                         }  
  71.                     }  
  72.                 }, 0100);  
  73.   
  74.             }  
  75.         });  
  76.     }  
  77.   
  78. }  

下载的工具类(DownUtil):

[java] view plaincopyprint?
  1. package com.home.util;  
  2.   
  3. import java.io.InputStream;  
  4. import java.io.RandomAccessFile;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7.   
  8. public class DownUtil {  
  9.     // 定义下载资源的路径  
  10.     private String path;  
  11.     // 指定所下载的文件的保存位置  
  12.     private String targetFile;  
  13.     // 定义需要使用多少线程下载资源  
  14.     private int threadNum;  
  15.     // 定义下载的文件的总大小  
  16.     private int fileSize;  
  17.     // 定义下载的线程对象  
  18.     private DownloadThread[] threads;  
  19.   
  20.     public DownUtil(String path, String targetFile, int threadNum) {  
  21.         this.path = path;  
  22.         this.threadNum = threadNum;  
  23.         // 初始化threads数组  
  24.         threads = new DownloadThread[threadNum];  
  25.         this.targetFile = targetFile;  
  26.     }  
  27.   
  28.     public void download() throws Exception {  
  29.         URL url = new URL(path);  
  30.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  31.         conn.setConnectTimeout(5 * 1000);  
  32.         conn.setRequestMethod("GET");  
  33.         conn.setRequestProperty(  
  34.                 "Accept",  
  35.                 "image/gif,image/jpeg,image/pjpeg,application/x-shockwaveflash,application/x-ms-xbap,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*");  
  36.         conn.setRequestProperty("Accept-Language""zh-CN");  
  37.         conn.setRequestProperty("Charset""UTF-8");  
  38.         conn.setRequestProperty(  
  39.                 "User-Agent",  
  40.                 "Mozilla/4.0(compatible;MSIE7.0;Windows NT 5.2;Trident/4.0;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30;.NET CLR 3.0.4506.2152;.NET CLR 3.5.30729)");  
  41.   
  42.         conn.setRequestProperty("Connection""Keep-Alive");  
  43.         // 得到文件大小  
  44.         fileSize = conn.getContentLength();  
  45.         conn.disconnect();  
  46.         int currentPartSize = fileSize / threadNum + 1;  
  47.         RandomAccessFile file = new RandomAccessFile(targetFile, "rw");  
  48.         // 设置本地文件的大小  
  49.         file.setLength(fileSize);  
  50.         file.close();  
  51.         for (int i = 0; i < threadNum; i++) {  
  52.             // 计算每条线程的下载的开始位置  
  53.             int startPos = i * currentPartSize;  
  54.             // 每个线程使用一个RandomAccessFile进行下载  
  55.             RandomAccessFile currentPart = new RandomAccessFile(targetFile,  
  56.                     "rw");  
  57.             // 定位该线程的下载位置  
  58.             currentPart.seek(startPos);  
  59.             // 创建下载线程  
  60.             threads[i] = new DownloadThread(startPos, currentPartSize,  
  61.                     currentPart);  
  62.             // 启动下载线程  
  63.             threads[i].start();  
  64.         }  
  65.     }  
  66.   
  67.     /**  
  68.      * 获取下载完成的百分比  
  69.      *   
  70.      * @return  
  71.      */  
  72.     public double getCompleteRate() {  
  73.         // 统计多条线程已经下载的总大小  
  74.         int sumSize = 0;  
  75.         for (int i = 0; i < threadNum; i++) {  
  76.             sumSize += threads[i].length;  
  77.         }  
  78.         // 返回已经完成的百分比  
  79.         return sumSize * 1.0 / fileSize;  
  80.     }  
  81.   
  82.     private class DownloadThread extends Thread {  
  83.         // 当前线程的下载位置  
  84.         private int startPos;  
  85.         // 定义当前线程负责下载的文件大小  
  86.         private int currentPartSize;  
  87.         // 当前线程需要下载的文件块  
  88.         private RandomAccessFile currentPart;  
  89.         // 定义该线程已下载的字节数  
  90.         private int length = 0;  
  91.   
  92.         public DownloadThread(int startPos, int currentPartSize,  
  93.                 RandomAccessFile currentPart) {  
  94.             this.startPos = startPos;  
  95.             this.currentPartSize = currentPartSize;  
  96.             this.currentPart = currentPart;  
  97.         }  
  98.   
  99.         public void run() {  
  100.             try {  
  101.                 URL url = new URL(path);  
  102.                 HttpURLConnection conn = (HttpURLConnection) url  
  103.                         .openConnection();  
  104.                 conn.setConnectTimeout(5 * 1000);  
  105.                 conn.setRequestMethod("GET");  
  106.                 conn.setRequestProperty(  
  107.                         "Accept",  
  108.                         "image/gif,image/jpeg,image/pjpeg,application/x-shockwaveflash,application/x-ms-xbap,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*");  
  109.                 conn.setRequestProperty("Accept-Language""zh-CN");  
  110.                 conn.setRequestProperty("Charset""UTF-8");  
  111.                 InputStream is = conn.getInputStream();  
  112.                 // 跳过startPos个字符,表明该线程只下载自己负责那部分文件  
  113.                 is.skip(startPos);  
  114.                 byte[] by = new byte[1024];  
  115.                 int hasRead = 0;  
  116.                 // 读取网络数据,并写入本地文件  
  117.                 while (length < currentPartSize  
  118.                         && (hasRead = is.read(by)) != -1) {  
  119.                     currentPart.write(by, 0, hasRead);  
  120.                     // 累计该线程下载的总大小  
  121.                     length += hasRead;  
  122.                 }  
  123.                 currentPart.close();  
  124.                 is.close();  
  125.             } catch (Exception e) {  
  126.                 e.printStackTrace();  
  127.             }  
  128.         }  
  129.     }  
  130. }  

Activity布局XML:

[html] view plaincopyprint?
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="vertical" >  
  5.   
  6.     <LinearLayout  
  7.         android:layout_width="match_parent"  
  8.         android:layout_height="wrap_content"  
  9.         android:orientation="horizontal" >  
  10.   
  11.         <TextView  
  12.             android:layout_width="wrap_content"  
  13.             android:layout_height="wrap_content"  
  14.             android:text="输入url:" />  
  15.   
  16.         <EditText  
  17.             android:id="@+id/main_et_url"  
  18.             android:layout_width="match_parent"  
  19.             android:layout_height="wrap_content" />  
  20.     </LinearLayout>  
  21.   
  22.     <LinearLayout  
  23.         android:layout_width="match_parent"  
  24.         android:layout_height="wrap_content"  
  25.         android:orientation="horizontal" >  
  26.   
  27.         <TextView  
  28.             android:layout_width="wrap_content"  
  29.             android:layout_height="wrap_content"  
  30.             android:text="输入保存的文件名:" />  
  31.   
  32.         <EditText  
  33.             android:id="@+id/main_et_name"  
  34.             android:layout_width="match_parent"  
  35.             android:layout_height="wrap_content" />  
  36.     </LinearLayout>  
  37.   
  38.     <Button  
  39.         android:id="@+id/main_btn_download"  
  40.         android:layout_width="wrap_content"  
  41.         android:layout_height="wrap_content"  
  42.         android:text="下载" />  
  43.   
  44.     <ProgressBar  
  45.         android:id="@+id/main_progressBar"  
  46.         style="@android:style/Widget.ProgressBar.Horizontal"  
  47.         android:layout_width="match_parent"  
  48.         android:layout_height="wrap_content" />  
  49.   
  50. </LinearLayout>  

权限:

[html] view plaincopyprint?
  1. <!-- 在SD卡中创建与删除文件权限 -->  
  2. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
  3. <!-- 向SD卡写入数据权限 -->  
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  5. <!-- 授权访问网络 -->  
  6. <uses-permission android:name="android.permission.INTERNET"/>  




 

更多0
3
1
0 0