萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 斷點續傳原理深度解析:HTTP Range 請求與 Java 實作完整指南

前言:什麼是斷點續傳?

斷點續傳 (Resumable Download) 允許用戶在網路中斷、暫停、重啟後,從已下載位置繼續下載,而非重頭開始。核心機制是 HTTP/1.1 Range 請求標頭與伺服器 206 Partial Content 回應。本文從協議層面解析原理,並提供 Java 完整實作範例。

協議層面原理:Range Request / Partial Content

1. 一般下載請求 (完整內容)

GET /largefile.zip HTTP/1.1
Host: example.com
User-Agent: MyDownloader/1.0
Accept: */*
Connection: keep-alive

伺服器回應:

HTTP/1.1 200 OK
Content-Length: 106786028
Accept-Ranges: bytes
Content-Type: application/octet-stream
Last-Modified: Mon, 30 Apr 2001 12:56:11 GMT
ETag: "abc123"
... (檔案內容) ...
Accept-Ranges: bytes 宣告伺服器支援位元組範圍請求。

2. 斷點續傳請求 (從位元組 2000070 繼續)

GET /largefile.zip HTTP/1.1
Host: example.com
User-Agent: MyDownloader/1.0
Range: bytes=2000070-
Accept: */*

關鍵標頭:Range: bytes=起始位元組-結束位元組 (結束可省略表「到檔案結尾」)。

3. 伺服器回應 206 Partial Content

HTTP/1.1 206 Partial Content
Content-Length: 104785958
Content-Range: bytes 2000070-106786027/106786028
Content-Type: application/octet-stream
ETag: "abc123"
Last-Modified: Mon, 30 Apr 2001 12:56:11 GMT
... (從位元組 2000070 開始的內容) ...

關鍵差異:

  • 狀態碼 206 (而非 200)。
  • Content-Range 指示本回應涵蓋範圍與總大小。
  • Content-Length 為本片段長度而非總長度。

4. 多範圍請求 (較少見)

Range: bytes=0-1023,2048-3071
# 回應為 multipart/byteranges

Java 實作:HttpURLConnection + RandomAccessFile

核心類別

  • java.net.HttpURLConnection:支援 setRequestProperty("Range", ...)。
  • java.io.RandomAccessFile:支援 seek(position) 定位寫入。

完整下載器類別

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class ResumableDownloader {

    public static void download(String urlStr, String destPath) throws IOException {
        File destFile = new File(destPath);
        long existingLen = destFile.exists() ? destFile.length() : 0L;

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", "ResumableDownloader/1.0");
        
        // 關鍵:設定 Range 標頭
        if (existingLen > 0) {
            conn.setRequestProperty("Range", "bytes=" + existingLen + "-");
        }

        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            // 伺服器不支援 Range,或檔案已變更 (ETag 不符)
            existingLen = 0; // 重頭下載
        } else if (responseCode != 206) {
            throw new IOException("Unexpected response code: " + responseCode);
        }

        // 取得總長度 (從 Content-Range 或 Content-Length)
        long totalLength;
        String contentRange = conn.getHeaderField("Content-Range");
        if (contentRange != null) {
            // 格式: bytes start-end/total
            totalLength = Long.parseLong(contentRange.split("/")[1]);
        } else {
            totalLength = conn.getContentLengthLong();
            if (existingLen > 0) totalLength += existingLen;
        }

        System.out.printf("下載: %s, 已有: %,d bytes, 總計: %,d bytes%n", destPath, existingLen, totalLength);

        try (InputStream in = conn.getInputStream();
             RandomAccessFile raf = new RandomAccessFile(destFile, "rw")) {

            raf.seek(existingLen); // 定位到續傳位置

            byte[] buffer = new byte[8192];
            int read;
            long downloaded = existingLen;
            long lastReport = System.currentTimeMillis();

            while ((read = in.read(buffer)) != -1) {
                raf.write(buffer, 0, read);
                downloaded += read;

                // 進度報告 (每秒)
                long now = System.currentTimeMillis();
                if (now - lastReport >= 1000) {
                    double pct = totalLength > 0 ? (downloaded * 100.0 / totalLength) : 0;
                    System.out.printf("\r進度: %,d / %,d (%.1f%%)", downloaded, totalLength, pct);
                    lastReport = now;
                }
            }
            System.out.println("\n下載完成。");
        } finally {
            conn.disconnect();
        }
    }

    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("用法: java ResumableDownloader  <輸出檔案路徑>");
            return;
        }
        try {
            download(args[0], args[1]);
        } catch (IOException e) {
            System.err.println("下載失敗: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

關鍵細節解析

  1. 檔案完整性驗證:下載完成後應比對 ETag 或 Last-Modified,確認檔案未在下載期間被伺服器端修改。若變更,需重頭下載。
  2. 暫停/繼續:單純中斷輸入流即可暫停,再次呼叫 download() 會自動偵測現有檔案大小並發送 Range 繼續。
  3. 多執行緒分段下載:將檔案分為 N 段,每段啟動一執行緒下載,合併時需同步寫入 RandomAccessFile 不同位置。
  4. 緩衝區大小:8KB-64KB 為宜,過大增加記憶體壓力,過小增加系統呼叫開銷。
  5. SSL/HTTPS:HttpsURLConnection 繼承 HttpURLConnection,用法相同,需注意憑證驗證。

伺服器端支援要求

並非所有伺服器預設支援 Range 請求。常見伺服器配置:

  • Nginx:預設開啟 sendfile on 並支援 Range。可用 max_ranges 限制多範圍請求數。
  • Apache:需載入 mod_headers、mod_setenvif,預設支援。
  • Tomcat / Spring Boot:靜態資源預設支援;ResourceHttpRequestHandler 處理 Range。
  • CDN/物件儲存 (S3/OSS):原生支援 Range,極適合大檔案分發。

進階主題

If-Range 條件請求

避免檔案在下載期間被修改導致合併檔案損壞:

If-Range: "abc123" (ETag)
If-Range: Mon, 30 Apr 2001 12:56:11 GMT (Last-Modified)

若條件符合 → 回應 206;否則 → 回應 200 全內容 (客戶端需捨棄舊檔重下)。

斷點續傳上傳 (Tus 協議 / HTTP PATCH)

上傳同樣需斷點續傳,標準化方案為 Tus.io 協議,使用 PATCH + Upload-Offset 標頭。HTTP 標準無原生上傳 Range 支援。

延伸閱讀

斷點續傳的核心極其簡單:Range 請求 + 206 Partial Content + RandomAccessFile.seek()。掌握協議細節與 Java 實作細節 (ETag 驗證、進度回報、錯誤重試、多執行緒分段),即可打造生產級下載元件,大幅提升大檔案傳輸可靠性與用戶體驗。

copyright © 萬盛學電腦網 all rights reserved