Java——HTTP多线程下载,端口侦听和自启动服务

把几个技术整合到了一起。包括三个部分,实现时也是逐个做到的 

多线程的文件下载,HTTP协议 

把这个功能做成一个HTTP的服务,侦听在某个端口上,方便非Java的系统使用 

把这个功能封装为一个Windows服务,在机器启动时可以自动启动 

我们逐个看程序。 

一、多线程下载 

这个主要使用了HTTP协议里面的一个Range参数,他设置了你读取数据的其实位置和终止位置。 经常使用flashget的用户在查看连接的详细信息时,应该经常看到这个东西。比如 

Range:bytes=100-2000 

代表从100个字节的位置开始读取,到2000个字节的位置结束,应读取1900个字节。 

程序首先拿到文件的长度,然后分配几个线程去分别读取各自的一段,使用了 

RandomAccessFile 

进行随机位置的读写。 

下面是完整的下载的代码。 

 1 package net.java2000.tools; 
 2 import java.io.BufferedInputStream; 
 3 import java.io.File; 
 4 import java.io.IOException; 
 5 import java.io.RandomAccessFile; 
 6 import java.net.URL; 
 7 import java.net.URLConnection; 
 8 /** 
 9 * HTTP的多线程下载工具。 
10 * 
11 * @author 赵学庆 www.java2000.net 
12 */ 
13 public class HTTPDownloader extends Thread { 
14   // 要下载的页面 
15   private String page; 
16   // 保存的路径 
17   private String savePath; 
18   // 线程数 
19   private int threadNumber = 2; 
20   // 来源地址 
21   private String referer; 
22   // 最小的块尺寸。如果文件尺寸除以线程数小于这个,则会减少线程数。 
23   private int MIN_BLOCK = 10 * 1024; 
24   public static void main(String[] args) throws Exception { 
25    HTTPDownloader d = new HTTPDownloader("http://www.xxxx.net/xxxx.rar", "d://xxxx.rar", 10); 
26    d.down(); 
27   } 
28   public void run() { 
29    try { 
30     down(); 
31    } catch (Exception e) { 
32     e.printStackTrace(); 
33    } 
34   } 
35   /** 
36   * 下载操作 
37   * 
38   * @throws Exception 
39   */ 
40   public void down() throws Exception { 
41    URL url = new URL(page); // 创建URL 
42    URLConnection con = url.openConnection(); // 建立连接 
43    int contentLen = con.getContentLength(); // 获得资源长度 
44    if (contentLen / MIN_BLOCK + 1 < threadNumber) { 
45     threadNumber = contentLen / MIN_BLOCK + 1; // 调整下载线程数 
46    } 
47    if (threadNumber > 10) { 
48     threadNumber = 10; 
49    } 
50    int begin = 0; 
51    int step = contentLen / threadNumber; 
52    int end = 0; 
53    for (int i = 0; i < threadNumber; i++) { 
54     end += step; 
55     if (end > contentLen) { 
56      end = contentLen; 
57     } 
58     new HTTPDownloaderThread(this, i, begin, end).start(); 
59     begin = end; 
60    } 
61   } 
62   public HTTPDownloader() { 
63   } 
64   /** 
65   * 下载 
66   * 
67   * @param page 被下载的页面 
68   * @param savePath 保存的路径 
69   */ 
70   public HTTPDownloader(String page, String savePath) { 
71    this(page, savePath, 10); 

 

 

 

posted @ 2012-12-28 20:26  freshier  阅读(351)  评论(0)    收藏  举报