2013年4月5日 星期五

[Java]透過HttpURLConnection進行檔案下載續傳

參考自這裡

一般瀏覽器對server發出的Request表頭如下:
GET /down.zip HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-
excel, application/msword, application/vnd.ms-powerpoint, */*
Accept-Language: zh-tw
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Connection: Keep-Alive

Server收到request之後,做出的回應表頭如下:
200
Content-Length=106786028
Accept-Ranges=bytes
Date=Mon, 30 Apr 2001 12:56:11 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:56:11 GMT


語法如下:

URL url = new URL("目標網址");
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection(); 
//設定 User-Agent 
httpConnection.setRequestProperty("User-Agent","NetFox"); 
//設定斷點續傳位置,"RANGE"
httpConnection.setRequestProperty("RANGE","bytes=2000070"); 
//取得輸入流
InputStream input = httpConnection.getInputStream();

//儲存檔案
RandomAccess oSavedFile = new RandomAccessFile("檔名","rw");
long nPos = 2000070;//原則上應該跟斷點的bytes數一樣
// 定位文件指標到nPos位置 
oSavedFile.seek(nPos); 
byte[] b = new byte[1024]; 
int nRead;
// 從輸入流中讀入文件,然後寫入 
while((nRead=input.read(b,0,1024)) > 0) 
{ 
oSavedFile.write(b,0,nRead); 
} 


沒有留言: