gpt4 book ai didi

android - 如何在 Retrofit 中获取 ContentLength

转载 作者:行者123 更新时间:2023-11-29 16:55:34 28 4
gpt4 key购买 nike

我在我的应用程序中使用了一项服务,我曾经改造它以在后台下载一些“apk”文件。我想用收到的文件大小检查下载的文件大小,以确保我完全获得“apk”。但是当我使用 response.body().contentLength() 时它是 -1!

这是我的代码:

 private void downloadAppFromServer(String url, final String fileId) {

APIService downloadService = ServiceGenerator.createServiceFile(APIService.class, "181412655", "181412655");

Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(url);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccess()) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {

Log.d("LOGO", "server contacted and has file");
Log.d("LOGO", "FILE SIZE: " + response.body().contentLength());


boolean writtenToDisk = writeResponseBodyToDisk(response.body(), fileId);
Log.d("LOGO", "file download was a success? " + writtenToDisk);

return null;
}
}.execute();

}
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {


});
}

这是我的 writeToDisk 方法:

 private boolean writeResponseBodyToDisk(ResponseBody body, String fileId) {

try {

// Location to save downloaded file and filename
File DownloadFile = new File(G.DIR_APK + "/" + fileId + ".apk");
InputStream inputStream = null;
OutputStream outputStream = null;
try {

byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
Log.d("LOGO", "file size is: " + fileSize ); //This is -1 !
outputStream = new FileOutputStream(DownloadFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
if (fileSize == fileSizeDownloaded) {
return true;
} else {
return false;
}
} catch (IOException e) {

return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}

} catch (IOException e) {
return false;
}
}

最佳答案

-1 表示网络服务器不给你任何关于文件长度的信息。

Retrofit 获取 header content-length。如果它不存在 response.body().contentLength() 返回 -1

关于android - 如何在 Retrofit 中获取 ContentLength,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45131268/

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