用Java实现断点续传(HTTP)

来源:互联网 发布:安卓系统编程设置re 编辑:程序博客网 时间:2024/05/20 16:12
 

用Java实现断点续传(HTTP)

    博客分类:
  • j2se
JavaBean浏览器IISthread
(一)断点续传的原理
其实断点续传的原理很简单,就是在Http的请求上和一般的下载有所不同而已。
打个比方,浏览器请求服务器上的一个文时,所发出的请求如下:
假设服务器域名为wwww.sjtu.edu.cn,文件名为down.zip。
GET /down.zip HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-
excel, application/msword, application/vnd.ms-powerpoint, */*
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Connection: Keep-Alive


服务器收到请求后,按要求寻找请求的文件,提取文件的信息,然后返回给浏览器,返回信息如下:


200
Content-Length=106786028
Accept-Ranges=bytes
Date=Mon, 30 Apr 2001 12:56:11 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:56:11 GMT


所谓断点续传,也就是要从文件已经下载的地方开始继续下载。所以在客户端浏览器传给
Web服务器的时候要多加一条信息--从哪里开始。
下面是用自己编的一个"浏览器"来传递请求信息给Web服务器,要求从2000070字节开始。
GET /down.zip HTTP/1.0
User-Agent: NetFox
RANGE: bytes=2000070-
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2


仔细看一下就会发现多了一行RANGE: bytes=2000070-
这一行的意思就是告诉服务器down.zip这个文件从2000070字节开始传,前面的字节不用传了。
服务器收到这个请求以后,返回的信息如下:
206
Content-Length=106786028
Content-Range=bytes 2000070-106786027/106786028
Date=Mon, 30 Apr 2001 12:55:20 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:55:20 GMT


和前面服务器返回的信息比较一下,就会发现增加了一行:
Content-Range=bytes 2000070-106786027/106786028
返回的代码也改为206了,而不再是200了。


知道了以上原理,就可以进行断点续传的编程了。


(二)Java实现断点续传的关键几点


(1)用什么方法实现提交RANGE: bytes=2000070-。
当然用最原始的Socket是肯定能完成的,不过那样太费事了,其实Java的net包中提供了这种功能。代码如下:
URL url = new URL("http://www.sjtu.edu.cn/down.zip");
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection


();
//设置User-Agent
httpConnection.setRequestProperty("User-Agent","NetFox");
//设置断点续传的开始位置
httpConnection.setRequestProperty("RANGE","bytes=2000070");
//获得输入流
InputStream input = httpConnection.getInputStream();


从输入流中取出的字节流就是down.zip文件从2000070开始的字节流。
大家看,其实断点续传用Java实现起来还是很简单的吧。
接下来要做的事就是怎么保存获得的流到文件中去了。


保存文件采用的方法。
我采用的是IO包中的RandAccessFile类。
操作相当简单,假设从2000070处开始保存文件,代码如下:
Java代码 复制代码 收藏代码
  1. RandomAccess oSavedFile = new RandomAccessFile("down.zip","rw");   
  2. long nPos = 2000070;   
  3. //定位文件指针到nPos位置   
  4. oSavedFile.seek(nPos);   
  5. byte[] b = new byte[1024];   
  6. int nRead;   
  7. //从输入流中读入字节流,然后写到文件中   
  8. while((nRead=input.read(b,0,1024)) > 0)   
  9. {   
  10. oSavedFile.write(b,0,nRead);   
  11. }  


怎么样,也很简单吧。
接下来要做的就是整合成一个完整的程序了。包括一系列的线程控制等等。



(三)断点续传内核的实现
主要用了6个类,包括一个测试类。
SiteFileFetch.java负责整个文件的抓取,控制内部线程(FileSplitterFetch类)。
FileSplitterFetch.java负责部分文件的抓取。
FileAccess.java负责文件的存储。
SiteInfoBean.java要抓取的文件的信息,如文件保存的目录,名字,抓取文件的URL等。
Utility.java工具类,放一些简单的方法。
TestMethod.java测试类。


下面是源程序:
Java代码 复制代码 收藏代码
  1. /*  
  2. **SiteFileFetch.java  
  3. */  
  4. package NetFox;   
  5. import java.io.*;   
  6. import java.net.*;   
  7.   
  8.   
  9. public class SiteFileFetch extends Thread {   
  10.   
  11.   
  12. SiteInfoBean siteInfoBean = null//文件信息Bean  
  13. long[] nStartPos; //开始位置  
  14. long[] nEndPos; //结束位置  
  15. FileSplitterFetch[] fileSplitterFetch; //子线程对象  
  16. long nFileLength; //文件长度  
  17. boolean bFirst = true//是否第一次取文件  
  18. boolean bStop = false//停止标志  
  19. File tmpFile; //文件下载的临时信息   
  20. DataOutputStream output; //输出到文件的输出流   
  21.   
  22.   
  23. public SiteFileFetch(SiteInfoBean bean) throws IOException   
  24. {   
  25. siteInfoBean = bean;   
  26. //tmpFile = File.createTempFile ("zhong","1111",new File(bean.getSFilePath()));  
  27. tmpFile = new File(bean.getSFilePath()+File.separator + bean.getSFileName()+".info");   
  28. if(tmpFile.exists ())   
  29. {   
  30. bFirst = false;   
  31. read_nPos();   
  32. }   
  33. else  
  34. {   
  35. nStartPos = new long[bean.getNSplitter()];   
  36. nEndPos = new long[bean.getNSplitter()];   
  37. }   
  38.   
  39.   
  40.   
  41. }   
  42.   
  43.   
  44. public void run()   
  45. {   
  46. //获得文件长度   
  47. //分割文件   
  48. //实例FileSplitterFetch   
  49. //启动FileSplitterFetch线程   
  50. //等待子线程返回   
  51. try{   
  52. if(bFirst)   
  53. {   
  54. nFileLength = getFileSize();   
  55. if(nFileLength == -1)   
  56. {   
  57. System.err.println("File Length is not known!");   
  58. }   
  59. else if(nFileLength == -2)   
  60. {   
  61. System.err.println("File is not access!");   
  62. }   
  63. else  
  64. {   
  65. for(int i=0;i<nStartPos.length;i++)   
  66. {   
  67. nStartPos[i] = (long)(i*(nFileLength/nStartPos.length));   
  68. }   
  69. for(int i=0;i<nEndPos.length-1;i++)   
  70. {   
  71. nEndPos[i] = nStartPos[i+1];   
  72. }   
  73. nEndPos[nEndPos.length-1] = nFileLength;   
  74. }   
  75. }   
  76.   
  77.   
  78. //启动子线程   
  79. fileSplitterFetch = new FileSplitterFetch[nStartPos.length];   
  80. for(int i=0;i<nStartPos.length;i++)   
  81. {   
  82. fileSplitterFetch[i] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),   
  83. siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),   
  84. nStartPos[i],nEndPos[i],i);   
  85. Utility.log("Thread " + i + " , nStartPos = " + nStartPos[i] + ", nEndPos = " + nEndPos[i]);   
  86. fileSplitterFetch[i].start();   
  87. }   
  88. // fileSplitterFetch[nPos.length-1] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),  
  89. siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(),nPos[nPos.length-1],nFileLength,nPos.length-1);   
  90. // Utility.log("Thread " + (nPos.length-1) + " , nStartPos = " + nPos[nPos.length-1] + ",  
  91. nEndPos = " + nFileLength);   
  92. // fileSplitterFetch[nPos.length-1].start();  
  93.   
  94.   
  95. //等待子线程结束   
  96. //int count = 0;   
  97. //是否结束while循环   
  98. boolean breakWhile = false;   
  99.   
  100.   
  101. while(!bStop)   
  102. {   
  103. write_nPos();   
  104. Utility.sleep(500);   
  105. breakWhile = true;   
  106.   
  107.   
  108. for(int i=0;i<nStartPos.length;i++)   
  109. {   
  110. if(!fileSplitterFetch[i].bDownOver)   
  111. {   
  112. breakWhile = false;   
  113. break;   
  114. }   
  115. }   
  116. if(breakWhile)   
  117. break;   
  118.   
  119.   
  120. //count++;   
  121. //if(count>4)   
  122. // siteStop();   
  123. }   
  124.   
  125.   
  126. System.err.println("文件下载结束!");   
  127. }   
  128. catch(Exception e){e.printStackTrace ();}   
  129. }   
  130.   
  131.   
  132. //获得文件长度   
  133. public long getFileSize()   
  134. {   
  135. int nFileLength = -1;   
  136. try{   
  137. URL url = new URL(siteInfoBean.getSSiteURL());   
  138. HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();   
  139. httpConnection.setRequestProperty("User-Agent","NetFox");   
  140.   
  141.   
  142. int responseCode=httpConnection.getResponseCode();   
  143. if(responseCode>=400)   
  144. {   
  145. processErrorCode(responseCode);   
  146. return -2//-2 represent access is error  
  147. }   
  148.   
  149.   
  150. String sHeader;   
  151.   
  152.   
  153. for(int i=1;;i++)   
  154. {   
  155. //DataInputStream in = new DataInputStream(httpConnection.getInputStream ());  
  156. //Utility.log(in.readLine());   
  157. sHeader=httpConnection.getHeaderFieldKey(i);   
  158. if(sHeader!=null)   
  159. {   
  160. if(sHeader.equals("Content-Length"))   
  161. {   
  162. nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));   
  163. break;   
  164. }   
  165. }   
  166. else  
  167. break;   
  168. }   
  169. }   
  170. catch(IOException e){e.printStackTrace ();}   
  171. catch(Exception e){e.printStackTrace ();}   
  172.   
  173.   
  174. Utility.log(nFileLength);   
  175.   
  176.   
  177. return nFileLength;   
  178. }   
  179.   
  180.   
  181. //保存下载信息(文件指针位置)   
  182. private void write_nPos()   
  183. {   
  184. try{   
  185. output = new DataOutputStream(new FileOutputStream(tmpFile));   
  186. output.writeInt(nStartPos.length);   
  187. for(int i=0;i<nStartPos.length;i++)   
  188. {   
  189. // output.writeLong(nPos[i]);   
  190. output.writeLong(fileSplitterFetch[i].nStartPos);   
  191. output.writeLong(fileSplitterFetch[i].nEndPos);   
  192. }   
  193. output.close();   
  194. }   
  195. catch(IOException e){e.printStackTrace ();}   
  196. catch(Exception e){e.printStackTrace ();}   
  197. }   
  198.   
  199.   
  200. //读取保存的下载信息(文件指针位置)   
  201. private void read_nPos()   
  202. {   
  203. try{   
  204. DataInputStream input = new DataInputStream(new FileInputStream(tmpFile));   
  205. int nCount = input.readInt();   
  206. nStartPos = new long[nCount];   
  207. nEndPos = new long[nCount];   
  208. for(int i=0;i<nStartPos.length;i++)   
  209. {   
  210. nStartPos[i] = input.readLong();   
  211. nEndPos[i] = input.readLong();   
  212. }   
  213. input.close();   
  214. }   
  215. catch(IOException e){e.printStackTrace ();}   
  216. catch(Exception e){e.printStackTrace ();}   
  217. }   
  218.   
  219.   
  220. private void processErrorCode(int nErrorCode)   
  221. {   
  222. System.err.println("Error Code : " + nErrorCode);   
  223. }   
  224.   
  225.   
  226. //停止文件下载   
  227. public void siteStop()   
  228. {   
  229. bStop = true;   
  230. for(int i=0;i<nStartPos.length;i++)   
  231. fileSplitterFetch[i].splitterStop();   
  232.   
  233.   
  234. }   
  235. }   
  236. /*  
  237. **FileSplitterFetch.java  
  238. */  
  239. package NetFox;   
  240.   
  241.   
  242. import java.io.*;   
  243. import java.net.*;   
  244.   
  245.   
  246. public class FileSplitterFetch extends Thread {   
  247.   
  248.   
  249. String sURL; //File URL   
  250. long nStartPos; //File Snippet Start Position  
  251. long nEndPos; //File Snippet End Position  
  252. int nThreadID; //Thread's ID  
  253. boolean bDownOver = false//Downing is over  
  254. boolean bStop = false//Stop identical  
  255. FileAccessI fileAccessI = null//File Access interface  
  256.   
  257.   
  258. public FileSplitterFetch(String sURL,String sName,long nStart,long nEnd,int id) throws IOException   
  259. {   
  260. this.sURL = sURL;   
  261. this.nStartPos = nStart;   
  262. this.nEndPos = nEnd;   
  263. nThreadID = id;   
  264. fileAccessI = new FileAccessI(sName,nStartPos);   
  265. }   
  266.   
  267.   
  268. public void run()   
  269. {   
  270. while(nStartPos < nEndPos && !bStop)   
  271. {   
  272.   
  273.   
  274. try{   
  275. URL url = new URL(sURL);   
  276. HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();   
  277. httpConnection.setRequestProperty("User-Agent","NetFox");   
  278. String sProperty = "bytes="+nStartPos+"-";   
  279. httpConnection.setRequestProperty("RANGE",sProperty);   
  280. Utility.log(sProperty);   
  281.   
  282.   
  283. InputStream input = httpConnection.getInputStream();   
  284. //logResponseHead(httpConnection);   
  285.   
  286.   
  287. byte[] b = new byte[1024];   
  288. int nRead;   
  289. while((nRead=input.read(b,0,1024)) > 0 && nStartPos < nEndPos && !bStop)   
  290. {   
  291. nStartPos += fileAccessI.write(b,0,nRead);   
  292. //if(nThreadID == 1)   
  293. // Utility.log("nStartPos = " + nStartPos + ", nEndPos = " + nEndPos);  
  294. }   
  295.   
  296.   
  297. Utility.log("Thread " + nThreadID + " is over!");   
  298. bDownOver = true;   
  299. //nPos = fileAccessI.write (b,0,nRead);   
  300. }   
  301. catch(Exception e){e.printStackTrace ();}   
  302. }   
  303. }   
  304.   
  305.   
  306. //打印回应的头信息   
  307. public void logResponseHead(HttpURLConnection con)   
  308. {   
  309. for(int i=1;;i++)   
  310. {   
  311. String header=con.getHeaderFieldKey(i);   
  312. if(header!=null)   
  313. //responseHeaders.put(header,httpConnection.getHeaderField(header));  
  314. Utility.log(header+" : "+con.getHeaderField(header));   
  315. else  
  316. break;   
  317. }   
  318. }   
  319.   
  320.   
  321. public void splitterStop()   
  322. {   
  323. bStop = true;   
  324. }   
  325.   
  326.   
  327. }   
  328.   
  329.   
  330. /*  
  331. **FileAccess.java  
  332. */  
  333. package NetFox;   
  334. import java.io.*;   
  335.   
  336.   
  337. public class FileAccessI implements Serializable{   
  338.   
  339.   
  340. RandomAccessFile oSavedFile;   
  341. long nPos;   
  342.   
  343.   
  344. public FileAccessI() throws IOException   
  345. {   
  346. this("",0);   
  347. }   
  348.   
  349.   
  350. public FileAccessI(String sName,long nPos) throws IOException   
  351. {   
  352. oSavedFile = new RandomAccessFile(sName,"rw");   
  353. this.nPos = nPos;   
  354. oSavedFile.seek(nPos);   
  355. }   
  356.   
  357.   
  358. public synchronized int write(byte[] b,int nStart,int nLen)   
  359. {   
  360. int n = -1;   
  361. try{   
  362. oSavedFile.write(b,nStart,nLen);   
  363. n = nLen;   
  364. }   
  365. catch(IOException e)   
  366. {   
  367. e.printStackTrace ();   
  368. }   
  369.   
  370.   
  371. return n;   
  372. }   
  373.   
  374.   
  375. }   
  376.   
  377.   
  378. /*  
  379. **SiteInfoBean.java  
  380. */  
  381. package NetFox;   
  382.   
  383.   
  384. public class SiteInfoBean {   
  385.   
  386.   
  387. private String sSiteURL; //Site's URL  
  388. private String sFilePath; //Saved File's Path  
  389. private String sFileName; //Saved File's Name  
  390. private int nSplitter; //Count of Splited Downloading File  
  391.   
  392.   
  393. public SiteInfoBean()   
  394. {   
  395. //default value of nSplitter is 5   
  396. this("","","",5);   
  397. }   
  398.   
  399.   
  400. public SiteInfoBean(String sURL,String sPath,String sName,int nSpiltter)   
  401. {   
  402. sSiteURL= sURL;   
  403. sFilePath = sPath;   
  404. sFileName = sName;   
  405. this.nSplitter = nSpiltter;   
  406.   
  407.   
  408. }   
  409.   
  410.   
  411. public String getSSiteURL()   
  412. {   
  413. return sSiteURL;   
  414. }   
  415.   
  416.   
  417. public void setSSiteURL(String value)   
  418. {   
  419. sSiteURL = value;   
  420. }   
  421.   
  422.   
  423. public String getSFilePath()   
  424. {   
  425. return sFilePath;   
  426. }   
  427.   
  428.   
  429. public void setSFilePath(String value)   
  430. {   
  431. sFilePath = value;   
  432. }   
  433.   
  434.   
  435. public String getSFileName()   
  436. {   
  437. return sFileName;   
  438. }   
  439.   
  440.   
  441. public void setSFileName(String value)   
  442. {   
  443. sFileName = value;   
  444. }   
  445.   
  446.   
  447. public int getNSplitter()   
  448. {   
  449. return nSplitter;   
  450. }   
  451.   
  452.   
  453. public void setNSplitter(int nCount)   
  454. {   
  455. nSplitter = nCount;   
  456. }   
  457. }   
  458.   
  459.   
  460. /*  
  461. **Utility.java  
  462. */  
  463. package NetFox;   
  464.   
  465.   
  466. public class Utility {   
  467.   
  468.   
  469. public Utility()   
  470. {   
  471.   
  472.   
  473. }   
  474.   
  475.   
  476. public static void sleep(int nSecond)   
  477. {   
  478. try{   
  479. Thread.sleep(nSecond);   
  480. }   
  481. catch(Exception e)   
  482. {   
  483. e.printStackTrace ();   
  484. }   
  485. }   
  486.   
  487.   
  488. public static void log(String sMsg)   
  489. {   
  490. System.err.println(sMsg);   
  491. }   
  492.   
  493.   
  494. public static void log(int sMsg)   
  495. {   
  496. System.err.println(sMsg);   
  497. }   
  498. }   
  499.   
  500.   
  501. /*  
  502. **TestMethod.java  
  503. */  
  504. package NetFox;   
  505.   
  506.   
  507. public class TestMethod {   
  508.   
  509.   
  510. public TestMethod()   
  511. ///xx/weblogic60b2_win.exe   
  512. try{   
  513. SiteInfoBean bean = new SiteInfoBean("http://localhost/xx/weblogic60b2_win.exe","L:\temp","weblogic60b2_win.exe",5);   
  514. //SiteInfoBean bean = new SiteInfoBean("http://localhost:8080/down.zip","L:\temp","weblogic60b2_win.exe",5);  
  515. SiteFileFetch fileFetch = new SiteFileFetch(bean);   
  516. fileFetch.start();   
  517. }   
  518. catch(Exception e){e.printStackTrace ();}   
  519.   
  520.   
  521. }   
  522.   
  523.   
  524. public static void main(String[] args)   
  525. {   
  526. new TestMethod();   
  527. }   
  528. }   

转自

http://wing929.iteye.com/blog/185529

原创粉丝点击