gpt4 book ai didi

android - 如何在 Android 中使用 okhttp 暂停/恢复下载

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:56 26 4
gpt4 key购买 nike

我使用 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。代码有什么问题?

最佳答案

第一种方式

我尝试了很多代码,最后我用 BufferedSource source = 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);
}

成功了。我觉得我很幸运:)

第二种方式

我为跳过下载的字节添加了 header ,它起作用了。

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);
}

关于android - 如何在 Android 中使用 okhttp 暂停/恢复下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43352569/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com