2017-04-11 116 views
4

我在android中使用okhttp庫下載文件。我下載成功。但是當我暫停並恢復下載時出現問題。如何使用okhttp在Android中暫停/恢復下載

Response request = new Request.Builder().url(url).build(); 
ResponseBody responseBody = response.body(); 

File file = new File(filePath); 
BufferedInputStream input = new BufferedInputStream(responseBody.byteStream()); 
OutputStream output; 

if (isResume) { 
    output = new FileOutputStream(file, true); 
    input.skip(downloadedSize); 
} else { 
    output = new FileOutputStream(file, false);  
} 

long totalByteSize = responseBody.contentLength(); 
byte[] data = new byte[1024]; 
int count = 0; 

while ((count = input.read(data)) != -1) { 
    downloadedSize += count; 
    output.write(data, 0, count); 
} 

的問題是,例如文件的大小是10MB。下載3MB後暫停,然後繼續下載,下載完成時文件大小變爲13MB。它不會從簡歷中下載大小開始,它會從字節流開始下載。所以文件變成13MB。代碼有什麼問題?

+1

您正在創建新請求併發送它。這導致響應保存整個文件。我不確定okHttp是否有能力下載部分回覆,但如果這樣做不是這樣。您至少必須傳遞一些關於從何處開始下載的數據。 –

回答

11

第一種方式

我嘗試了很多碼的,最後我BufferedSource源= responseBody.source解決(); source.skip(downloadedSize);

Response request = new Request.Builder().url(url).build(); 
ResponseBody responseBody = response.body(); 
BufferedSource source = responseBody.source(); 

if(isResume) 
    source.skip(downloadedSize); 

File file = new File(filePath); 
BufferedInputStream input = new BufferedInputStream(responseBody.byteStream()); 
OutputStream output; 

if (isResume) { 
    output = new FileOutputStream(file, true); 
} else { 
    output = new FileOutputStream(file, false);  
} 

long currentDownloadedSize = 0; 
long currentTotalByteSize = responseBody.contentLength(); 
byte[] data = new byte[1024]; 
int count = 0; 
while ((count = input.read(data)) != -1) { 
    currentDownloadedSize += count; 
    output.write(data, 0, count); 
} 

它工作成功。我覺得我很幸運:)

第二種方式

我添加了跳過下載字節的頭和它的工作。

Request.Builder requestBuilder = new Request.Builder(); 
if (isResume) { 
    requestBuilder.addHeader("Range", "bytes=" + String.valueOf(downloadedSize) + "-"); 
} 
Response request = requestBuilder.url(url).build(); 
ResponseBody responseBody = response.body(); 
BufferedSource source = responseBody.source(); 

File file = new File(filePath); 
BufferedInputStream input = new BufferedInputStream(responseBody.byteStream()); 
OutputStream output; 

if (isResume) { 
    output = new FileOutputStream(file, true); 
} else { 
    output = new FileOutputStream(file, false);  
} 

long currentDownloadedSize = 0; 
long currentTotalByteSize = responseBody.contentLength(); 
byte[] data = new byte[1024]; 
int count = 0; 
while ((count = input.read(data)) != -1) { 
    currentDownloadedSize += count; 
    output.write(data, 0, count); 
}