0

I am downloading a file via OkHttp3. When I get back the Response response as a result of calling .newCall().execute(), I am writing the response to the Android device's disk as so:

//https://stackoverflow.com/a/29012988/4672234
File targetFile = MyFileManager.getMyFile(context);
BufferedSink sink = Okio.buffer(Okio.sink(targetFile));
sink.writeAll(response.body().source());
sink.close();

I'm observing strange behavior in some clients where the file will be entirely downloaded, then while they are attempting to write the file to disk, there is a network error. At that time the write to disk is interrupted and I'm left with only part of the file on the file system.

I don't mind the network errors - this is unsurprising as several clients are in very poor network coverage. And with cheap devices. I want to avoid a situation where the network connection is trying to be kept open while the device is writing to disk.

I realize I maybe postulating - is OkHttp leaving the http connection open while I'm writing the file to disk? If so how do I work around this issue - read all of the data into memory immediately, close the OkHttp response, then write that to disk?

Steve
  • 538
  • 4
  • 17

1 Answers1

1

You can ask the stream to buffer the entire response.


BufferedSource source =  response.body().source();
source.request(Long.MAX_VALUE);

File targetFile = MyFileManager.getMyFile(context);
BufferedSink sink = Okio.buffer(Okio.sink(targetFile));
sink.writeAll(source);
sink.close();
Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • Could you explain how this functionally differs from the original code? Does requesting that the BufferedSource buffer the entire response result in the HTTP connection being closed thereafter? I attempted to call response.close() immediately after source.request(Long.MAX_VALUE) but that breaks the write to the sink so I think I'm missing the point. – Steve May 18 '23 at 13:54
  • 1
    By reading the entire HTTP response before writing any of the file, you prevent network problems from occurring while writing the file. – Jesse Wilson May 22 '23 at 11:54