1. Overview

This tutorial is going to illustrate how to download a file with OkHttp, an HTTP & HTTP/2 client for Android and Java applications, powered by Square.

We can download a file synchronously and asynchronously with OkHttp. With asynchronous download, the file is download on a worker thread, and get called back when the response is readable.

The version of OkHttp used in this tutorial is 3.4.1. Maven dependency for it can be declared as below:

2. Download a file with OkHttp synchronously

Here is the sample source code to download a file synchronously then write the file temporarily to disk.

We just need to create an OkHttpClient instance, build a request with given URL, execute the request and get back the response.

3. Download a file with OkHttp asynchronously

Here is the sample code to download a file asynchronously then write it to disk.

The difference with synchronous downloading is after creating a new OkHttpClient instance and build the Request object, instead of calling the execute() method, we call the enqueue() method to schedule the request to be executed at some point in the future. Note that we also need to pass a Callback object to the the enqueue() method for later call back with either an HTTP response or a failure exception.

4. Conclusion

These simple examples show how to download a file with OkHttp by issuing both synchronous and asynchronous requests.

The sample source code can be found in my Github repository or you can download it at here. And below are other related OkHttp tutorials for your reference:

OkHttp Post Examples

Java REST Client Examples Using OkHttp

Basic Authentication with OkHttp Example

Upload a File with OkHttp

Set Timeout with OkHttp

WebSocket Client Example with OkHttp

How to Cache Response with OkHttp

5 1 vote
Article Rating