萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

斷點續傳原理深度解析:HTTP Range 請求、響應與 Java 實現全流程

斷點續傳核心在於 HTTP Range 請求頭與 Content-Range 響應頭的協作。本文從協議層面解析請求/響應報文差異,並提供 Java HttpURLConnection + RandomAccessFile 完整實現代碼。

協議層面原理

普通下載請求

GET /down.zip HTTP/1.1
Host: www.example.com
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: "02ca57e173c11:95b"

斷點續傳請求 (從 2000070 字節開始)

GET /down.zip HTTP/1.0
User-Agent: NetFox
Range: bytes=2000070-
Accept: */*
關鍵:Range: bytes=起始位置- 表示從指定位置到結尾;bytes=0-1023 表示前 1KB。

斷點續傳響應

HTTP/1.1 206 Partial Content
Content-Length: 104785958
Content-Range: bytes 2000070-106786027/106786028
Content-Type: application/octet-stream
Last-Modified: Mon, 30 Apr 2001 12:55:20 GMT
ETag: "02ca57e173c11:95b"
關鍵差異:狀態碼 206 Partial Content、新增 Content-Range 標識返回片段範圍與總長度。

Java 實現核心代碼

1. 發送 Range 請求獲取輸入流

URL url = new URL("https://www.example.com/down.zip");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// 設置 User-Agent (部分服務器校驗)
conn.setRequestProperty("User-Agent", "NetFox/1.0");

// 核心:設置斷點位置
long resumePosition = 2000070L;
conn.setRequestProperty("Range", "bytes=" + resumePosition + "-");

// 獲取輸入流 (已是斷點位置的字節流)
InputStream in = conn.getInputStream();

2. RandomAccessFile 定位寫入實現續傳

RandomAccessFile raf = new RandomAccessFile("down.zip", "rw");

// 定位檔案指針到斷點位置
raf.seek(resumePosition);

byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) > 0) {
    raf.write(buffer, 0, len)
}

in.close();
raf.close();

完整可運行類結構

public class ResumeDownloader {
    public static void download(String urlStr, String destFile, long resumeFrom) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Range", "bytes=" + resumeFrom + "-");
        
        try (InputStream in = conn.getInputStream();
             RandomAccessFile raf = new RandomAccessFile(destFile, "rw")) {
            
            raf.seek(resumeFrom);
            byte[] buf = new byte[8192];
            int n;
            while ((n = in.read(buf)) != -1) {
                raf.write(buf, 0, n);
            }
        }
    }
}

生產級增強點

  • 多線程分段下載:將檔案分為 N 段,並發下載合併
  • 斷點記錄持久化:定期記錄已下載位移,支援崩潰恢復
  • 校驗完整性:下載完成後驗證 MD5/SHA256 或 ETag
  • 限速與優先級:ThrottledInputStream + 線程池優先級
  • 代理/認證支援:Authenticator + ProxySelector

斷點續傳 HTTP 交互圖

現代替代方案:curl -C - -O URL (自動續傳)、wget -c URL、aria2c (多線程/金屬鏈/種子支援) 已足夠應對絕大多數場景,手寫 Java 僅供教學或特殊嵌入需求。
copyright © 萬盛學電腦網 all rights reserved