Skip to main content

How to download a file using OKHTTP in Kotlin Android

How to download a file using OKHTTP in Kotlin Android.

In this tutorial, we will learn how to download a file using OkHttp library in Kotlin Android. OkHttp is a powerful HTTP client for Android that makes it easy to consume RESTful APIs and perform network operations.

Step 1: Add OkHttp Dependency

To get started, we need to add the OkHttp dependency to our project. Open your project's build.gradle file and add the following line to the dependencies block:

implementation 'com.squareup.okhttp3:okhttp:4.9.0'

Sync your project to download the dependency.

Step 2: Create a Download Manager Class

Create a new Kotlin class called DownloadManager that will handle the file download operation. Inside the class, add the following code:

import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class DownloadManager {

private val client = OkHttpClient()

fun downloadFile(url: String, destination: String, callback: DownloadCallback) {
val request = Request.Builder()
.url(url)
.build()

client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
callback.onError(e.message)
}

override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
callback.onError("Unexpected response code: ${response.code}")
return
}

val file = File(destination)
val inputStream = response.body?.byteStream()
val outputStream = FileOutputStream(file)

inputStream?.use { input ->
outputStream.use { output ->
val buffer = ByteArray(4096)
var bytesRead: Int
while (input.read(buffer).also { bytesRead = it } != -1) {
output.write(buffer, 0, bytesRead)
}
output.flush()
}
}

callback.onSuccess()
}
})
}

interface DownloadCallback {
fun onSuccess()
fun onError(message: String?)
}
}

The DownloadManager class encapsulates the file download logic. It uses OkHttp's OkHttpClient to make the network request and handles the response using OkHttp's Callback. The downloaded file is saved to the specified destination file path.

Step 3: Download the File

To download a file using the DownloadManager class, you can create an instance of it and call the downloadFile function. Here's an example:

val downloadManager = DownloadManager()

val url = "https://example.com/file.pdf"
val destination = "/path/to/save/file.pdf"

downloadManager.downloadFile(url, destination, object : DownloadManager.DownloadCallback {
override fun onSuccess() {
// File downloaded successfully
}

override fun onError(message: String?) {
// Error occurred during file download
}
})

Replace the url variable with the actual URL of the file you want to download, and set the destination variable to the desired file path to save the downloaded file.

The DownloadCallback interface provides callbacks for handling the download success and failure scenarios.

Summary

In this tutorial, we have learned how to download a file using OkHttp library in Kotlin Android. We created a DownloadManager class that encapsulates the file download logic and used OkHttp's OkHttpClient and Callback to perform the network request and handle the response.