斷點續傳 (Resumable Download) 允許用戶在網路中斷、暫停、重啟後,從已下載位置繼續下載,而非重頭開始。核心機制是 HTTP/1.1 Range 請求標頭與伺服器 206 Partial Content 回應。本文從協議層面解析原理,並提供 Java 完整實作範例。
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 宣告伺服器支援位元組範圍請求。
GET /largefile.zip HTTP/1.1
Host: example.com
User-Agent: MyDownloader/1.0
Range: bytes=2000070-
Accept: */*
關鍵標頭:Range: bytes=起始位元組-結束位元組 (結束可省略表「到檔案結尾」)。
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 開始的內容) ...
關鍵差異:
Content-Range 指示本回應涵蓋範圍與總大小。Content-Length 為本片段長度而非總長度。Range: bytes=0-1023,2048-3071
# 回應為 multipart/byteranges
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();
}
}
}
ETag 或 Last-Modified,確認檔案未在下載期間被伺服器端修改。若變更,需重頭下載。download() 會自動偵測現有檔案大小並發送 Range 繼續。RandomAccessFile 不同位置。HttpsURLConnection 繼承 HttpURLConnection,用法相同,需注意憑證驗證。並非所有伺服器預設支援 Range 請求。常見伺服器配置:
sendfile on 並支援 Range。可用 max_ranges 限制多範圍請求數。mod_headers、mod_setenvif,預設支援。ResourceHttpRequestHandler 處理 Range。避免檔案在下載期間被修改導致合併檔案損壞:
If-Range: "abc123" (ETag)
If-Range: Mon, 30 Apr 2001 12:56:11 GMT (Last-Modified)
若條件符合 → 回應 206;否則 → 回應 200 全內容 (客戶端需捨棄舊檔重下)。
上傳同樣需斷點續傳,標準化方案為 Tus.io 協議,使用 PATCH + Upload-Offset 標頭。HTTP 標準無原生上傳 Range 支援。
斷點續傳的核心極其簡單:Range 請求 + 206 Partial Content + RandomAccessFile.seek()。掌握協議細節與 Java 實作細節 (ETag 驗證、進度回報、錯誤重試、多執行緒分段),即可打造生產級下載元件,大幅提升大檔案傳輸可靠性與用戶體驗。