斷點續傳核心在於 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"
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 標識返回片段範圍與總長度。
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();
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);
}
}
}
}
ThrottledInputStream + 線程池優先級Authenticator + ProxySelector
現代替代方案:curl -C - -O URL(自動續傳)、wget -c URL、aria2c(多線程/金屬鏈/種子支援) 已足夠應對絕大多數場景,手寫 Java 僅供教學或特殊嵌入需求。