Android通过HTTP协议实现断点续传下载

来源:互联网 发布:网络直播评论性文章 编辑:程序博客网 时间:2024/06/06 01:52
  1.  // FileDownloader.java                                                                      package cn.itcast.net.download;  
  2.   
  3. import java.io.File;  
  4. import java.io.RandomAccessFile;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.util.LinkedHashMap;  
  8. import java.util.Map;  
  9. import java.util.UUID;  
  10. import java.util.concurrent.ConcurrentHashMap;  
  11. import java.util.regex.Matcher;  
  12. import java.util.regex.Pattern;  
  13. import cn.itcast.service.FileService;  
  14.   
  15. import android.content.Context;  
  16. import android.util.Log;  
  17. /** 
  18.  * 文件下载器 
  19.  * FileDownloader loader = new FileDownloader(context, "http://browse.babasport.com/ejb3/ActivePort.exe", 
  20.                 new File("D:\\androidsoft\\test"), 2); 
  21.         loader.getFileSize();//得到文件总大小 
  22.         try { 
  23.             loader.download(new DownloadProgressListener(){ 
  24.                 public void onDownloadSize(int size) { 
  25.                     print("已经下载:"+ size); 
  26.                 }            
  27.             }); 
  28.         } catch (Exception e) { 
  29.             e.printStackTrace(); 
  30.         } 
  31.  */  
  32. public class FileDownloader {  
  33.     private static final String TAG = "FileDownloader";  
  34.     private Context context;  
  35.     private FileService fileService;      
  36.     /* 已下载文件长度 */  
  37.     private int downloadSize = 0;  
  38.     /* 原始文件长度 */  
  39.     private int fileSize = 0;  
  40.     /* 线程数 */  
  41.     private DownloadThread[] threads;  
  42.     /* 本地保存文件 */  
  43.     private File saveFile;  
  44.     /* 缓存各线程下载的长度*/  
  45.     private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();  
  46.     /* 每条线程下载的长度 */  
  47.     private int block;  
  48.     /* 下载路径  */  
  49.     private String downloadUrl;  
  50.     /** 
  51.      * 获取线程数 
  52.      */  
  53.     public int getThreadSize() {  
  54.         return threads.length;  
  55.     }  
  56.     /** 
  57.      * 获取文件大小 
  58.      * @return 
  59.      */  
  60.     public int getFileSize() {  
  61.         return fileSize;  
  62.     }  
  63.     /** 
  64.      * 累计已下载大小 
  65.      * @param size 
  66.      */  
  67.     protected synchronized void append(int size) {  
  68.         downloadSize += size;  
  69.     }  
  70.     /** 
  71.      * 更新指定线程最后下载的位置 
  72.      * @param threadId 线程id 
  73.      * @param pos 最后下载的位置 
  74.      */  
  75.     protected synchronized void update(int threadId, int pos) {  
  76.         this.data.put(threadId, pos);  
  77.         this.fileService.update(this.downloadUrl, this.data);  
  78.     }  
  79.     /** 
  80.      * 构建文件下载器 
  81.      * @param downloadUrl 下载路径 
  82.      * @param fileSaveDir 文件保存目录 
  83.      * @param threadNum 下载线程数 
  84.      */  
  85.     public FileDownloader(Context context, String downloadUrl, File fileSaveDir, int threadNum) {  
  86.         try {  
  87.             this.context = context;  
  88.             this.downloadUrl = downloadUrl;  
  89.             fileService = new FileService(this.context);  
  90.             URL url = new URL(this.downloadUrl);  
  91.             if(!fileSaveDir.exists()) fileSaveDir.mkdirs();  
  92.             this.threads = new DownloadThread[threadNum];                     
  93.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  94.             conn.setConnectTimeout(5*1000);  
  95.             conn.setRequestMethod("GET");  
  96.             conn.setRequestProperty("Accept""image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");  
  97.             conn.setRequestProperty("Accept-Language""zh-CN");  
  98.             conn.setRequestProperty("Referer", downloadUrl);   
  99.             conn.setRequestProperty("Charset""UTF-8");  
  100.             conn.setRequestProperty("User-Agent""Mozilla/4.0 (compatible; MSIE 8.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)");  
  101.             conn.setRequestProperty("Connection""Keep-Alive");  
  102.             conn.connect();  
  103.             printResponseHeader(conn);  
  104.             if (conn.getResponseCode()==200) {  
  105.                 this.fileSize = conn.getContentLength();//根据响应获取文件大小  
  106.                 if (this.fileSize <= 0throw new RuntimeException("Unkown file size ");  
  107.                           
  108.                 String filename = getFileName(conn);//获取文件名称  
  109.                 this.saveFile = new File(fileSaveDir, filename);//构建保存文件  
  110.                 Map<Integer, Integer> logdata = fileService.getData(downloadUrl);//获取下载记录  
  111.                 if(logdata.size()>0){//如果存在下载记录  
  112.                     for(Map.Entry<Integer, Integer> entry : logdata.entrySet())  
  113.                         data.put(entry.getKey(), entry.getValue());//把各条线程已经下载的数据长度放入data中  
  114.                 }  
  115.                 if(this.data.size()==this.threads.length){//下面计算所有线程已经下载的数据长度  
  116.                     for (int i = 0; i < this.threads.length; i++) {  
  117.                         this.downloadSize += this.data.get(i+1);  
  118.                     }  
  119.                     print("已经下载的长度"this.downloadSize);  
  120.                 }  
  121.                 //计算每条线程下载的数据长度  
  122.                 this.block = (this.fileSize % this.threads.length)==0this.fileSize / this.threads.length : this.fileSize / this.threads.length + 1;  
  123.             }else{  
  124.                 throw new RuntimeException("server no response ");  
  125.             }  
  126.         } catch (Exception e) {  
  127.             print(e.toString());  
  128.             throw new RuntimeException("don't connection this url");  
  129.         }  
  130.     }  
  131.     /**  
  132.      * 获取文件名  
  133.      */  
  134.     private String getFileName(HttpURLConnection conn) {  
  135.         String filename = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);  
  136.         if(filename==null || "".equals(filename.trim())){//如果获取不到文件名称  
  137.             for (int i = 0;; i++) {  
  138.                 String mine = conn.getHeaderField(i);  
  139.                 if (mine == nullbreak;  
  140.                 if("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())){  
  141.                     Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());  
  142.                     if(m.find()) return m.group(1);  
  143.                 }  
  144.             }  
  145.             filename = UUID.randomUUID()+ ".tmp";//默认取一个文件名  
  146.         }  
  147.         return filename;  
  148.     }  
  149.       
  150.     /** 
  151.      *  开始下载文件 
  152.      * @param listener 监听下载数量的变化,如果不需要了解实时下载的数量,可以设置为null 
  153.      * @return 已下载文件大小 
  154.      * @throws Exception 
  155.      */  
  156.     public int download(DownloadProgressListener listener) throws Exception{  
  157.         try {  
  158.             RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");  
  159.             if(this.fileSize>0) randOut.setLength(this.fileSize);  
  160.             randOut.close();  
  161.             URL url = new URL(this.downloadUrl);  
  162.             if(this.data.size() != this.threads.length){  
  163.                 this.data.clear();  
  164.                 for (int i = 0; i < this.threads.length; i++) {  
  165.                     this.data.put(i+10);//初始化每条线程已经下载的数据长度为0  
  166.                 }  
  167.             }  
  168.             for (int i = 0; i < this.threads.length; i++) {//开启线程进行下载  
  169.                 int downLength = this.data.get(i+1);  
  170.                 if(downLength < this.block && this.downloadSize<this.fileSize){//判断线程是否已经完成下载,否则继续下载    
  171.                     this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);  
  172.                     this.threads[i].setPriority(7);  
  173.                     this.threads[i].start();  
  174.                 }else{  
  175.                     this.threads[i] = null;  
  176.                 }  
  177.             }  
  178.             this.fileService.save(this.downloadUrl, this.data);  
  179.             boolean notFinish = true;//下载未完成  
  180.             while (notFinish) {// 循环判断所有线程是否完成下载  
  181.                 Thread.sleep(900);  
  182.                 notFinish = false;//假定全部线程下载完成  
  183.                 for (int i = 0; i < this.threads.length; i++){  
  184.                     if (this.threads[i] != null && !this.threads[i].isFinish()) {//如果发现线程未完成下载  
  185.                         notFinish = true;//设置标志为下载没有完成  
  186.                         if(this.threads[i].getDownLength() == -1){//如果下载失败,再重新下载  
  187.                             this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);  
  188.                             this.threads[i].setPriority(7);  
  189.                             this.threads[i].start();  
  190.                         }  
  191.                     }  
  192.                 }                 
  193.                 if(listener!=null) listener.onDownloadSize(this.downloadSize);//通知目前已经下载完成的数据长度  
  194.             }  
  195.             fileService.delete(this.downloadUrl);  
  196.         } catch (Exception e) {  
  197.             print(e.toString());  
  198.             throw new Exception("file download fail");  
  199.         }  
  200.         return this.downloadSize;  
  201.     }  
  202.     /** 
  203.      * 获取Http响应头字段 
  204.      * @param http 
  205.      * @return 
  206.      */  
  207.     public static Map<String, String> getHttpResponseHeader(HttpURLConnection http) {  
  208.         Map<String, String> header = new LinkedHashMap<String, String>();  
  209.         for (int i = 0;; i++) {  
  210.             String mine = http.getHeaderField(i);  
  211.             if (mine == nullbreak;  
  212.             header.put(http.getHeaderFieldKey(i), mine);  
  213.         }  
  214.         return header;  
  215.     }  
  216.     /** 
  217.      * 打印Http头字段 
  218.      * @param http 
  219.      */  
  220.     public static void printResponseHeader(HttpURLConnection http){  
  221.         Map<String, String> header = getHttpResponseHeader(http);  
  222.         for(Map.Entry<String, String> entry : header.entrySet()){  
  223.             String key = entry.getKey()!=null ? entry.getKey()+ ":" : "";  
  224.             print(key+ entry.getValue());  
  225.         }  
  226.     }  
  227.   
  228.     private static void print(String msg){  
  229.         Log.i(TAG, msg);  
  230.     }  
  231. }  

DownloadThread.Java

[java] view plain copy
  1. package cn.itcast.net.download;  
  2.   
  3. import java.io.File;  
  4. import java.io.InputStream;  
  5. import java.io.RandomAccessFile;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import android.util.Log;  
  10.   
  11. public class DownloadThread extends Thread {  
  12.     private static final String TAG = "DownloadThread";  
  13.     private File saveFile;  
  14.     private URL downUrl;  
  15.     private int block;  
  16.     /* 下载开始位置  */  
  17.     private int threadId = -1;    
  18.     private int downLength;  
  19.     private boolean finish = false;  
  20.     private FileDownloader downloader;  
  21.   
  22.     public DownloadThread(FileDownloader downloader, URL downUrl, File saveFile, int block, int downLength, int threadId) {  
  23.         this.downUrl = downUrl;  
  24.         this.saveFile = saveFile;  
  25.         this.block = block;  
  26.         this.downloader = downloader;  
  27.         this.threadId = threadId;  
  28.         this.downLength = downLength;  
  29.     }  
  30.       
  31.     @Override  
  32.     public void run() {  
  33.         if(downLength < block){//未下载完成  
  34.             try {  
  35.                 HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();  
  36.                 http.setConnectTimeout(5 * 1000);  
  37.                 http.setRequestMethod("GET");  
  38.                 http.setRequestProperty("Accept""image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");  
  39.                 http.setRequestProperty("Accept-Language""zh-CN");  
  40.                 http.setRequestProperty("Referer", downUrl.toString());   
  41.                 http.setRequestProperty("Charset""UTF-8");  
  42.                 int startPos = block * (threadId - 1) + downLength;//开始位置  
  43.                 int endPos = block * threadId -1;//结束位置  
  44.                 http.setRequestProperty("Range""bytes=" + startPos + "-"+ endPos);//设置获取实体数据的范围  
  45.                 http.setRequestProperty("User-Agent""Mozilla/4.0 (compatible; MSIE 8.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)");  
  46.                 http.setRequestProperty("Connection""Keep-Alive");  
  47.                   
  48.                 InputStream inStream = http.getInputStream();  
  49.                 byte[] buffer = new byte[1024];  
  50.                 int offset = 0;  
  51.                 print("Thread " + this.threadId + " start download from position "+ startPos);  
  52.                 RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");  
  53.                 threadfile.seek(startPos);  
  54.                 while ((offset = inStream.read(buffer, 01024)) != -1) {  
  55.                     threadfile.write(buffer, 0, offset);  
  56.                     downLength += offset;  
  57.                     downloader.update(this.threadId, downLength);  
  58.                     downloader.append(offset);  
  59.                 }  
  60.                 threadfile.close();  
  61.                 inStream.close();  
  62.                 print("Thread " + this.threadId + " download finish");  
  63.                 this.finish = true;  
  64.             } catch (Exception e) {  
  65.                 this.downLength = -1;  
  66.                 print("Thread "this.threadId+ ":"+ e);  
  67.             }  
  68.         }  
  69.     }  
  70.     private static void print(String msg){  
  71.         Log.i(TAG, msg);  
  72.     }  
  73.     /**  
  74.      * 下载是否完成  
  75.      * @return  
  76.      */  
  77.     public boolean isFinish() {  
  78.         return finish;  
  79.     }  
  80.     /** 
  81.      * 已经下载的内容大小 
  82.      * @return 如果返回值为-1,代表下载失败 
  83.      */  
  84.     public long getDownLength() {  
  85.         return downLength;  
  86.     }  
  87. }  

DownloadProgressListener.java

[java] view plain copy
  1. package cn.itcast.net.download;  
  2.   
  3. public interface DownloadProgressListener {  
  4.     public void onDownloadSize(int size);  
  5. }  

DBOpenHelper.java

[java] view plain copy
  1. package cn.itcast.service;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.   
  7. public class DBOpenHelper extends SQLiteOpenHelper {  
  8.     private static final String DBNAME = "itcast.db";  
  9.     private static final int VERSION = 1;  
  10.       
  11.     public DBOpenHelper(Context context) {  
  12.         super(context, DBNAME, null, VERSION);  
  13.     }  
  14.       
  15.     @Override  
  16.     public void onCreate(SQLiteDatabase db) {  
  17.         db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, downlength INTEGER)");  
  18.     }  
  19.   
  20.     @Override  
  21.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  22.         db.execSQL("DROP TABLE IF EXISTS filedownlog");  
  23.         onCreate(db);  
  24.     }  
  25.   
  26. }  

FileService.java

[java] view plain copy
  1. package cn.itcast.service;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.Map;  
  5.   
  6. import android.content.Context;  
  7. import android.database.Cursor;  
  8. import android.database.sqlite.SQLiteDatabase;  
  9. /** 
  10.  * 业务bean 
  11.  * 
  12.  */  
  13. public class FileService {  
  14.     private DBOpenHelper openHelper;  
  15.   
  16.     public FileService(Context context) {  
  17.         openHelper = new DBOpenHelper(context);  
  18.     }  
  19.     /** 
  20.      * 获取每条线程已经下载的文件长度 
  21.      * @param path 
  22.      * @return 
  23.      */  
  24.     public Map<Integer, Integer> getData(String path){  
  25.         SQLiteDatabase db = openHelper.getReadableDatabase();  
  26.         Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?"new String[]{path});  
  27.         Map<Integer, Integer> data = new HashMap<Integer, Integer>();  
  28.         while(cursor.moveToNext()){  
  29.             data.put(cursor.getInt(0), cursor.getInt(1));  
  30.         }  
  31.         cursor.close();  
  32.         db.close();  
  33.         return data;  
  34.     }  
  35.     /** 
  36.      * 保存每条线程已经下载的文件长度 
  37.      * @param path 
  38.      * @param map 
  39.      */  
  40.     public void save(String path,  Map<Integer, Integer> map){//int threadid, int position  
  41.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  42.         db.beginTransaction();  
  43.         try{  
  44.             for(Map.Entry<Integer, Integer> entry : map.entrySet()){  
  45.                 db.execSQL("insert into filedownlog(downpath, threadid, downlength) values(?,?,?)",  
  46.                         new Object[]{path, entry.getKey(), entry.getValue()});  
  47.             }  
  48.             db.setTransactionSuccessful();  
  49.         }finally{  
  50.             db.endTransaction();  
  51.         }  
  52.         db.close();  
  53.     }  
  54.     /** 
  55.      * 实时更新每条线程已经下载的文件长度 
  56.      * @param path 
  57.      * @param map 
  58.      */  
  59.     public void update(String path, Map<Integer, Integer> map){  
  60.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  61.         db.beginTransaction();  
  62.         try{  
  63.             for(Map.Entry<Integer, Integer> entry : map.entrySet()){  
  64.                 db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?",  
  65.                         new Object[]{entry.getValue(), path, entry.getKey()});  
  66.             }  
  67.             db.setTransactionSuccessful();  
  68.         }finally{  
  69.             db.endTransaction();  
  70.         }  
  71.         db.close();  
  72.     }  
  73.     /** 
  74.      * 当文件下载完成后,删除对应的下载记录 
  75.      * @param path 
  76.      */  
  77.     public void delete(String path){  
  78.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  79.         db.execSQL("delete from filedownlog where downpath=?"new Object[]{path});  
  80.         db.close();  
  81.     }  
  82.       
  83. }  

DownloadActivity.java

[java] view plain copy
  1. package cn.itcast.download;  
  2.   
  3. import java.io.File;  
  4.   
  5. import cn.itcast.net.download.DownloadProgressListener;  
  6. import cn.itcast.net.download.FileDownloader;  
  7.   
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.os.Environment;  
  11. import android.os.Handler;  
  12. import android.os.Message;  
  13. import android.view.View;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.ProgressBar;  
  17. import android.widget.TextView;  
  18. import android.widget.Toast;  
  19.   
  20. public class DownloadActivity extends Activity {  
  21.     private EditText downloadpathText;  
  22.     private TextView resultView;  
  23.     private ProgressBar progressBar;  
  24.     //当Handler被创建会关联到创建它的当前线程的消息队列,该类用于往消息队列发送消息  
  25.     //消息队列中的消息由当前线程内部进行处理  
  26.     private Handler handler = new Handler(){  
  27.   
  28.         @Override  
  29.         public void handleMessage(Message msg) {              
  30.             switch (msg.what) {  
  31.             case 1:               
  32.                 progressBar.setProgress(msg.getData().getInt("size"));  
  33.                 float num = (float)progressBar.getProgress()/(float)progressBar.getMax();  
  34.                 int result = (int)(num*100);  
  35.                 resultView.setText(result+ "%");  
  36.                 if(progressBar.getProgress()==progressBar.getMax()){  
  37.                     Toast.makeText(DownloadActivity.this, R.string.success, 1).show();  
  38.                 }  
  39.                 break;  
  40.   
  41.             case -1:  
  42.                 Toast.makeText(DownloadActivity.this, R.string.error, 1).show();  
  43.                 break;  
  44.             }  
  45.         }  
  46.     };  
  47.       
  48.     @Override  
  49.     public void onCreate(Bundle savedInstanceState) {  
  50.         super.onCreate(savedInstanceState);  
  51.         setContentView(R.layout.main);  
  52.           
  53.         downloadpathText = (EditText) this.findViewById(R.id.downloadpath);  
  54.         progressBar = (ProgressBar) this.findViewById(R.id.downloadbar);  
  55.         resultView = (TextView) this.findViewById(R.id.result);  
  56.         Button button = (Button) this.findViewById(R.id.button);  
  57.         button.setOnClickListener(new View.OnClickListener() {            
  58.             @Override  
  59.             public void onClick(View v) {  
  60.                 String path = downloadpathText.getText().toString();  
  61.                 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
  62.                     download(path, Environment.getExternalStorageDirectory());  
  63.                 }else{  
  64.                     Toast.makeText(DownloadActivity.this, R.string.sdcarderror, 1).show();  
  65.                 }  
  66.                   
  67.             }  
  68.         });  
  69.     }  
  70.     //主线程(UI线程)  
  71.     //业务逻辑正确,但是该程序运行的时候有问题  
  72.     //对于显示控件的界面更新只是由UI线程负责,如果是在非UI线程更新控件的属性值,更新后的显示界面不会反映到屏幕上  
  73.     private void download(final String path, final File savedir) {  
  74.         new Thread(new Runnable() {           
  75.             @Override  
  76.             public void run() {  
  77.                 FileDownloader loader = new FileDownloader(DownloadActivity.this, path, savedir, 3);  
  78.                 progressBar.setMax(loader.getFileSize());//设置进度条的最大刻度为文件的长度  
  79.                 try {  
  80.                     loader.download(new DownloadProgressListener() {  
  81.                         @Override  
  82.                         public void onDownloadSize(int size) {//实时获知文件已经下载的数据长度  
  83.                             Message msg = new Message();  
  84.                             msg.what = 1;  
  85.                             msg.getData().putInt("size", size);  
  86.                             handler.sendMessage(msg);//发送消息  
  87.                         }  
  88.                     });  
  89.                 } catch (Exception e) {  
  90.                     handler.obtainMessage(-1).sendToTarget();  
  91.                 }  
  92.             }  
  93.         }).start();  
  94.     }  
  95. }  
阅读全文
0 0