我嘗試下載一個檔案并檢查是否已整體下載:
Request request = new Request.Builder().url("http://example.com/myfile.tar.gz").build();
Response response = client.newCall(request).execute();
// Status code checks goes here
if (downloadedTar == null) {
throw new SettingsFailedException();
}
ResponseBody downloadedTar = response.body();
double contentLength = Double.parseDouble(response.header("content-length"));
File file = File.createTempFile(System.currentTimeMillis() "_file", ".tar.gz", getContext().getCacheDir());
FileOutputStream download = new FileOutputStream(file);
download.write(downloadedTar.body().bytes());
download.flush();
download.close();
if(file.exists() && (double)file.length() == contentLength){
// file has been downloaded
}
但這一行:
double contentLength = Double.parseDouble(response.header("content-length"));
但是response.header("content-length")是空,沒有整數值,我也試過以下變化response.header("Content-Length")和response.header("Content-Length")沒有任何成功。
那么為什么我無法檢索 Content-Length 標頭以及如何確保該檔案已成功下載?
uj5u.com熱心網友回復:
Content-Length 在許多情況下被洗掉,例如 Gzip 回應
https://github.com/square/okhttp/blob/3ad1912f783e108b3d0ad2c4a5b1b89b827e4db9/okhttp/src/jvmMain/kotlin/okhttp3/internal/http/BridgeInterceptor.kt#L98
但通常不能保證流式回應(h2 的分塊)存在。
您應該盡量避免要求內容長度,因為它保證存在并且可能會更改。您也可以使用以下方法優化您的 IO
Okio.buffer(Okio.sink(file)).writeAll(response.body().source())
或科特林
file.sink().buffer().writeAll(response.body!!.source())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/401717.html
