Home > Net >  OkHttp3 How I can retrieve the Http Content Length from http header?
OkHttp3 How I can retrieve the Http Content Length from http header?

Time:01-02

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.

So why I cannot retrieve Content-Length header and how I can ensure that file has been sucessfully downloaded?

CodePudding user response:

Content-Length is removed in a number of cases such as Gzip responses

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).

You should try to avoid requiring content-length as it is guaranteed to be present and may change. Also you can probably optimise your IO with

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

or kotlin

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

  • Related