[英]OkHttp3 How I can retrieve the Http Content Length from http header?
I try to download a file and check whether has been downloaded as a whole:我尝试下载一个文件并检查是否已整体下载:
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
}
But the line:但是这条线:
double contentLength = Double.parseDouble(response.header("content-length"));
But response.header("content-length")
is Null and has no integer value, I also tried the following variation response.header("Content-Length")
and response.header("Content-Length")
without any success.但是response.header("content-length")
是 Null 并且没有 integer 值,我也尝试了以下变体response.header("Content-Length")
和response.header("Content-Length")
没有任何成功。
So why I cannot retrieve Content-Length header and how I can ensure that file has been sucessfully downloaded?那么为什么我无法检索 Content-Length header 以及如何确保该文件已成功下载?
Content-Length is removed in a number of cases such as Gzip responses Content-Length 在许多情况下被删除,例如 Gzip 响应
https://github.com/square/okhttp/blob/3ad1912f783e108b3d0ad2c4a5b1b89b827e4db9/okhttp/src/jvmMain/kotlin/okhttp3/internal/http/BridgeInterceptor.kt#L98 https://github.com/square/okhttp/blob/3ad1912f783e108b3d0ad2c4a5b1b89b827e4db9/okhttp/src/jvmMain/kotlin/okhttp3/internal/http/BridgeInterceptor.kt#L98
But generally isn't guaranteed to be present for streamed responses (chunked of h2).但通常不能保证出现流式响应(h2 分块)。
You should try to avoid requiring content-length as it is guaranteed to be present and may change.您应该尽量避免要求 content-length,因为它保证存在并且可能会更改。 Also you can probably optimise your IO with你也可以优化你的 IO
file.sink().buffer().writeAll(response.body.!.source())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.