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:
1 2 3 4 5 |
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.4.1</version> </dependency> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
public void downloadFileSync(String downloadUrl) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(downloadUrl).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Failed to download file: " + response); } FileOutputStream fos = new FileOutputStream("d:/tmp.txt"); fos.write(response.body().bytes()); fos.close(); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public void downloadFileAsync(final String downloadUrl) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(downloadUrl).build(); client.newCall(request).enqueue(new Callback() { public void onFailure(Call call, IOException e) { e.printStackTrace(); } public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { throw new IOException("Failed to download file: " + response); } FileOutputStream fos = new FileOutputStream("d:/tmp.txt"); fos.write(response.body().bytes()); fos.close(); } }); } |
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:
Java REST Client Examples Using OkHttp
Basic Authentication with OkHttp Example
WebSocket Client Example with OkHttp
How to Cache Response with OkHttp