HttpURLconnection多线程下载

import java.io.BufferedInputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;

public class FileDownloadTest {
private static final int THREAD_COUNT = 10;
private CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
private long completeLength = 0;
private long fileLength;

// 进行下载的线程
class DownloadThread extends Thread {
private URL url;
private RandomAccessFile file;
private long from;
private long end;

/**
* @param url
* 下载的URL
* @param file
* 下载完成之后存储的文件
* @param from
* 当前线程对应文件的起始位置
* @param end
* 当前线程对应文件的结束位置
*/
DownloadThread(URL url, RandomAccessFile file, long from, long end) {
this.url = url;
this.file = file;
this.from = from;
this.end = end;
}

public void run() {
try {
long pos = from;
byte[] buf = new byte[1024];

HttpURLConnection cn = (HttpURLConnection) url.openConnection();

// 因为有些网站根据它判断是否是盗链接
cn.setRequestProperty("Referer", "http://www.ibook8.com");

// 设置请求的起始和结束位置。
cn.setRequestProperty("Range", "bytes=" + from + "-" + end);

// 如果请求错误,重试。
if (cn.getResponseCode() != 200 && cn.getResponseCode() != 206) {
System.out
.println("Responce Code: " + cn.getResponseCode());
run();
return;
}
BufferedInputStream bis = new BufferedInputStream(cn
.getInputStream());
int len;
while ((len = bis.read(buf)) > 0) {
synchronized (file) {
file.seek(pos);
file.write(buf, 0, len);
}
pos += len;
completeLength += len;
System.out.println(completeLength * 100 / fileLength + "%");
}
cn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
latch.countDown();
}
}

public void download(String address) throws Exception {
URL url = new URL(address);
URLConnection cn = url.openConnection();
cn.setRequestProperty("Referer", "http://www.ibook8.com");
fileLength = cn.getContentLength();
long packageLength = fileLength / THREAD_COUNT;
long leftLength = fileLength % THREAD_COUNT;

RandomAccessFile file = new RandomAccessFile("sapco.rar", "rw");

System.out.println(fileLength);
// 计算每个线程请求的起始位置和结束位置。
long pos = 0;
for (int i = 0; i < THREAD_COUNT; i++) {
long endPos = pos + packageLength;

if (leftLength > 0) {
endPos++;
leftLength--;
}
new DownloadThread(url, file, pos, endPos).start();
pos = endPos;
}
latch.await();
}

public static void main(String[] args) throws Exception {
long time = System.currentTimeMillis();
new FileDownloadTest()
.download("http://vip.ibook8.com/2008/7/sapco.rar");
System.out.println(System.currentTimeMillis() - time);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值