Skip to main content

How to download files using Retrofit in Kotlin Android

How to download files using Retrofit in Kotlin Android.

Here's a detailed step-by-step tutorial on how to download files using Retrofit in Kotlin Android.

Step 1: Add Retrofit and OkHttp Dependencies

First, you need to add the Retrofit and OkHttp dependencies to your project's build.gradle file.

dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
}

Step 2: Create a Retrofit Service Interface

Next, create a service interface that defines the API endpoints for downloading files. This interface will use Retrofit annotations to specify the HTTP method, URL, and other details.

interface FileDownloadService {
@GET
@Streaming
suspend fun downloadFile(@Url url: String): ResponseBody
}

In this example, we use the @GET annotation to specify the HTTP GET method, and @Streaming to indicate that we want to download a large file. The @Url annotation is used to dynamically pass the file URL.

Step 3: Create a Retrofit Instance

Now, create a Retrofit instance with the base URL of the API.

val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(OkHttpClient())
.build()

val service = retrofit.create(FileDownloadService::class.java)

Replace BASE_URL with the base URL of the API you're working with. The OkHttpClient is used as the HTTP client for making network requests.

Step 4: Download the File

To download a file, you can simply call the downloadFile function on the Retrofit service interface.

val url = "https://example.com/file.txt"
val response = service.downloadFile(url)

In this example, we pass the URL of the file we want to download. The downloadFile function will return a ResponseBody object, which represents the raw file data.

Step 5: Save the File

To save the downloaded file, you can use the response.body()?.byteStream() method to get an InputStream from the ResponseBody. You can then use this stream to write the file data to a local file.

val inputStream = response.body()?.byteStream()
val outputFile = File(context.filesDir, "file.txt")

inputStream?.let {
outputFile.outputStream().use { fileOut ->
inputStream.copyTo(fileOut)
}
}

In this example, we create a File object to represent the output file location. We then use the copyTo extension function to copy the file data from the input stream to the output file.

Step 6: Handle Errors and Progress

You can also handle errors and track the download progress by adding appropriate code. For example, you can handle network errors by wrapping the download code in a try-catch block.

try {
val response = service.downloadFile(url)
// Save the file
} catch (e: Exception) {
// Handle the error
}

To track the download progress, you can use the response.body()?.contentLength() method to get the total file size, and then monitor the number of bytes read from the input stream.

val contentLength = response.body()?.contentLength()
val inputStream = response.body()?.byteStream()
val outputFile = File(context.filesDir, "file.txt")

inputStream?.let {
outputFile.outputStream().use { fileOut ->
val buffer = ByteArray(4096)
var bytesRead = inputStream.read(buffer)
var totalBytesRead = bytesRead

while (bytesRead != -1) {
fileOut.write(buffer, 0, bytesRead)
bytesRead = inputStream.read(buffer)
totalBytesRead += bytesRead

// Calculate progress percentage
val progress = (totalBytesRead.toDouble() / contentLength!!) * 100

// Update UI with progress
}
}
}

In this example, we use a buffer to read the file data in chunks, and update the progress based on the total bytes read.

That's it! You now have a step-by-step tutorial on how to download files using Retrofit in Kotlin Android. You can customize the code as per your requirements and handle additional functionality as needed.