http多线程下载


        http文件下载已经是一个非常常用的功能,最近在linux使用axel进行文件下载时,使用到了多线程下载,发现下载速度非常快,因此想用java实现一下http协议的多线程下载。

        借用google查看了网上的资料(http://blog.csdn.net/zhuhuiby/article/details/6725951) ,发现http多线程下载是借用了http协议中Range参数实现的,自己写了个下载实现。

       关键代码如下:


         1,需要通过http协议返回的数据长度,确认数据量是多少,

         /**
* 获取下载文件的大小

* @param url
* @return
* @throws IOException
*/
private static int getSize(URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setRequestMethod("GET");
int i = conn.getContentLength();
conn.disconnect();
return i;
}

       2,借用Range,根据下载的数据长度,下载文件,例如下载0-1024字节

        public void download(DownloadTask po) throws IOException {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) po.url.openConnection();
conn.setConnectTimeout(3 * 1000);
// conn.setReadTimeout(timeout);
conn.setRequestMethod("GET");


int start = po.start;
// 指定网络位置从什么位置开始下载,到什么位置结束
conn.setRequestProperty("Range", String.format(farmmat, start, (start + po.length)));
InputStream in = conn.getInputStream();// 获得输入流


int i = 0;
while ((i = in.read(buff)) > 0) {
po.writer.write(buff, start, i);
start += i;
}
} finally {
// 下载完成之后,减少计数器
po.count.less();
// 当计数器为0时,则认为数据已经下载完成,关闭文件写入器。
if (po.count.getValue() == 0) {
po.writer.close();
}
conn.disconnect();
}
}


    3,采用随机写文件的方式将数据写入到文件,注意,线程安全:

          /**
* 写文件,写采用同步写。

* @param buff
* @param start
* @param length
* @throws IOException
*/
public synchronized void write(byte[] buff, int start, int length) throws IOException {
accessFile.seek(start);
accessFile.write(buff, 0, length);


}

   相关代码可从 http://download.csdn.net/detail/lkclkc88/7789135 获取,本人能力有限,不保证代码完全正确,代码未经大量测试,只可用于参考,并且代码仍有大量可优化的地方。

       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值