JAVA多线程下载,断点续传(HTTP)

HTTP的断点续传其实很简单,就是通过设置Header (RANGE: bytes=XXXXXXXX- )

1, 通常的HTTP请求

public static void main(String[] args) {

        try {
            URL url = new URL("http://mirrors.cnnic.cn/apache/abdera/1.1.3/apache-abdera-1.1.3-bin.zip");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            //con.setRequestProperty("RANGE", "bytes=100-");
            con.setRequestMethod("HEAD");
            con.connect();
            Map<String, List<String>> header = con.getHeaderFields();
            Iterator<String> keyIt = header.keySet().iterator();
            while(keyIt.hasNext()){
                String key = keyIt.next();
                List<String> values = header.get(key);
                System.out.print(key+":");
                for (String value:values) {
                    System.out.print(value);

                }
                System.out.println();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

这时候的输出:


Last-Modified:Sat, 14 Jun 2014 16:32:17 GMT
null:HTTP/1.1 200 OK
Server:nginx
ETag:"539c7911-d21551"
Content-Length:13768017
Accept-Ranges:bytes
Connection:keep-alive
Content-Type:application/zip
Date:Fri, 13 May 2016 09:58:20 GMT


返回的相应码是200,
#2,在请求的HEAD中添加RANGE:bytes=XXXXX-
如果添加con.setRequestProperty("RANGE", "bytes=100-");
下面是输出结果:


Last-Modified:Sat, 14 Jun 2014 16:32:17 GMT
null:HTTP/1.1 206 Partial Content
Server:nginx
ETag:"539c7911-d21551"
Content-Range:bytes 100-13768016/13768017
Content-Length:13767917
Connection:keep-alive
Content-Type:application/zip
Date:Fri, 13 May 2016 10:00:16 GMT
</P>
这次的响应码是206, 并且在response中返回了Content-Range:bytes 100-13768016/13768017
这个100-13768016是这个可以下载的大小,13768017是文件大小。此时的Content-Length:13767917不是文件大小,而是13768016-100=13767917,此时可以下载的大小。
#3, 多线程下载文件
多线程下载的原理就是,多个线程同时发送请求通过在head 添加RANGE:bytes=XXXXX-
比如线程1设置RANGE:bytes=1000-,线程2设置RANGE:bytes=2000- 等等
#4,断点续传
断点续传是把每个线程下的位置保存一个文件,下次在请求的时候从没有下载的地方开始
#5,简单实现
程序结构:


multithread.png


源码:github
测试代码:


public static void main(String[] args) {
DownLoader dl = DownLoader.getInstance();
dl.setUrl("http://mirrors.cnnic.cn/apache/abdera/1.1.3/apache-abdera-1.1.3-bin.zip");
dl.setOnDownLoadListener(new DownLoaderListener() {
@Override
public void onError(String arg0) {
System.out.println(arg0);
}
@Override
public void onFinish(String arg0) {
System.out.println(arg0);
}
@Override
public void onUpgrade(float arg0) {
System.out.println(arg0);
}
});
dl.setThreadCount(3);
dl.start();
}

程序有很多不足,请多多指教,谢谢!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JAVA多线程实现断点续传的思路如下: 1. 将大文件均分成几块,每个线程负责处理一块数据的读取和写入。 2. 每次写入数据时,更新记录的日志文件,记录已经传输的字节数或块数。 3. 当断网或暂停后重新开始传输时,根据日志文件的信息,可以接着读取和写入数据,而不需要从头开始传输。 以下是一个JAVA多线程实现断点续传的示例代码: ```java import java.io.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FileTransfer { private static final int THREAD_COUNT = 4; // 线程数量 private static final String LOG_FILE = "transfer.log"; // 日志文件名 private static final String SOURCE_FILE = "source.txt"; // 源文件名 private static final String TARGET_FILE = "target.txt"; // 目标文件名 public static void main(String[] args) { // 读取日志文件,获取已传输的字节数 long transferredBytes = readLogFile(); // 创建线程池 ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); // 计算每个线程需要处理的字节数 long blockSize = new File(SOURCE_FILE).length() / THREAD_COUNT; // 创建并执行线程 for (int i = 0; i < THREAD_COUNT; i++) { long start = i * blockSize + transferredBytes; long end = (i + 1) * blockSize - 1; if (i == THREAD_COUNT - 1) { end = new File(SOURCE_FILE).length() - 1; } executorService.execute(new TransferThread(i, start, end)); } // 关闭线程池 executorService.shutdown(); } private static long readLogFile() { long transferredBytes = 0; try { File logFile = new File(LOG_FILE); if (logFile.exists()) { BufferedReader reader = new BufferedReader(new FileReader(logFile)); String line; while ((line = reader.readLine()) != null) { transferredBytes += Long.parseLong(line); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } return transferredBytes; } private static void writeLogFile(long transferredBytes) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(LOG_FILE, true)); writer.write(String.valueOf(transferredBytes)); writer.newLine(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } private static class TransferThread implements Runnable { private int threadId; private long start; private long end; public TransferThread(int threadId, long start, long end) { this.threadId = threadId; this.start = start; this.end = end; } @Override public void run() { try { RandomAccessFile sourceFile = new RandomAccessFile(SOURCE_FILE, "r"); RandomAccessFile targetFile = new RandomAccessFile(TARGET_FILE, "rw"); sourceFile.seek(start); targetFile.seek(start); byte[] buffer = new byte[1024]; int bytesRead; long transferredBytes = 0; while ((bytesRead = sourceFile.read(buffer)) != -1 && sourceFile.getFilePointer() <= end) { targetFile.write(buffer, 0, bytesRead); transferredBytes += bytesRead; } writeLogFile(transferredBytes); sourceFile.close(); targetFile.close(); } catch (IOException e) { e.printStackTrace(); } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值