我在我的应用程序中使用了一项服务,我曾经对其进行改造以在后台下载一些“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) {
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
-1 意味着 Web 服务器不会为您提供有关文件长度的任何信息。
改造获得 header content-length。如果不存在则response.body().contentLength()返回-1。
| 归档时间: |
|
| 查看次数: |
3161 次 |
| 最近记录: |