代码之家  ›  专栏  ›  技术社区  ›  Dimitrios Desyllas

OkHttp3如何从Http头检索Http内容长度?

  •  0
  • Dimitrios Desyllas  · 技术社区  · 4 年前

    我尝试下载一个文件,并检查是否已整体下载:

    
    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") 为Null并且没有整数值,我还尝试了以下变化 response.header("Content-Length") 和 回答标题(“内容长度”) 没有任何成功。

    那个么,为什么我无法检索内容长度标题,以及如何确保文件已成功下载?

    0 回复  |  直到 4 年前
        1
  •  1
  •   Yuri Schimke    4 年前

    在许多情况下,如Gzip响应,都会删除内容长度

    https://github.com/square/okhttp/blob/3ad1912f783e108b3d0ad2c4a5b1b89b827e4db9/okhttp/src/jvmMain/kotlin/okhttp3/internal/http/BridgeInterceptor.kt#L98

    但通常不能保证流式响应(h2块)存在。

    您应该尽量避免要求内容长度,因为它保证存在并且可能会更改。此外,您还可以使用

    Okio.buffer(Okio.sink(file)).writeAll(response.body().source())

    还是科特林

    file.sink().buffer().writeAll(response.body!!.source())