Android下使用Http协议实现多线程断点续传下载
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
0.使用多线程下载会提升文件下载的速度,那么多线程下载文件的过程是:
(1)首先获得下载文件的长度,然后设置本地文件的长度
HttpURLConnection.getContentLength();
RandomAccessFile file = new RandomAccessFile("QQWubiSetup.exe","rwd");
file.setLength(filesize);//设置本地文件的长度
(2)根据文件长度和线程数计算每条线程下载的数据长度和下载位置。
如:文件的长度为6M,线程数为3,那么,每条线程下载的数据长度为2M,每条线程开始下载的位置如下图所示。
例如10M大小,使用3个线程来下载,
线程下载的数据长度 (10%3 == 0 ? 10/3:10/3+1) ,第1,2个线程下载长度是4M,第三个线程下载长度为2M
下载开始位置:线程id*每条线程下载的数据长度 = ?
下载结束位置:(线程id+1)*每条线程下载的数据长度-1=?
(3)使用Http的Range头字段指定每条线程从文件的什么位置开始下载,下载到什么位置为止,
如:指定从文件的2M位置开始下载,下载到位置(4M-1byte)为止
代码如下:HttpURLConnection.setRequestProperty("Range",
"bytes=2097152-4194303");
(4)保存文件,使用RandomAccessFile类指定每条线程从本地文件的什么位置开始写入数据。
RandomAccessFile threadfile = new RandomAccessFile("QQWubiSetup.exe ","rwd");
threadfile.seek(2097152);//从文件的什么位置开始写入数据
1.多线程下载的核心代码示例
Java代码
1.public class MulThreadDownload
2.{
3. /**
4. * 多线程下载
5. * @param args
6. */
7. public static void main(String[] args)
8. {
9. String path = "/QQWubiSetup.exe";
10. try
11. {
12. new MulThreadDownload().download(path, 3);
13. }
14. catch (Exception e)
15. {
16. e.printStackTrace();
17. }
18. }
19. /**
20. * 从路径中获取文件名称
21. * @param path 下载路径
22. * @return
23. */
24. public static String getFilename(String path)
25. {
26. return path.substring(stIndexOf('/')+1);
27. }
28. /**
29. * 下载文件
30. * @param path 下载路径
31. * @param threadsize 线程数
32. */
33. public void download(String path, int threadsize) throws
Exception
34. {
35. URL url = new URL(path);
36. HttpURLConnection conn = (HttpURLConnection)url.openC
onnection();
37. conn.setRequestMethod("GET");
38. conn.setConnectTimeout(5 * 1000);
39. //获取要下载的文件的长度
40. int filelength = conn.getContentLength();
41. //从路径中获取文件名称
42. String filename = getFilename(path);
43. File saveFile = new File(filename);
44. RandomAccessFile accessFile = new RandomAccessFile(sa
veFile, "rwd");
45. //设置本地文件的长度和下载文件相同
46. accessFile.setLength(filelength);
47. accessFile.close();
48. //计算每条线程下载的数据长度
49. int block = filelength%threadsize==0? filelength/thre
adsize : filelength/threadsize+1;
50. for(int threadid=0 ; threadid < threadsize ; threadid
++){
51. new DownloadThread(url, saveFile, block, threadid
).start();
52. }
53. }
54.
55. private final class DownloadThread extends Thread
56. {
57. private URL url;
58. private File saveFile;
59. private int block;//每条线程下载的数据长度
60. private int threadid;//线程id
61. public DownloadThread(URL url, File saveFile, int blo
ck, int threadid)
62. {
63. this.url = url;
64. this.saveFile = saveFile;
65. this.block = block;
66. this.threadid = threadid;
67. }
68.@Override
69. public void run()
70. {
71. //计算开始位置公式:线程id*每条线程下载的数据长度
= ?
72. //计算结束位置公式:(线程id +1)*每条线程下载的数
据长度-1 =?
73. int startposition = threadid * block;
74. int endposition = (threadid + 1 ) * block - 1;