Skip to main content

How to set custom headers for file downloads using DownloadManager in Kotlin Android

How to set custom headers for file downloads using DownloadManager in Kotlin Android.

Here's a step-by-step tutorial on how to set custom headers for file downloads using DownloadManager in Kotlin Android:

Step 1: Add permissions to manifest file

First, you need to add the necessary permissions to your AndroidManifest.xml file. Open the file and add the following lines:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

These permissions are required to access the internet and write files to external storage.

Step 2: Create a function to download a file

Next, create a function in your activity or fragment that will handle the file download. Here's an example of how you can do this:

private fun downloadFile(url: String, headers: Map<String, String>?) {
val request = DownloadManager.Request(Uri.parse(url))

// Set custom headers
headers?.forEach { (key, value) ->
request.addRequestHeader(key, value)
}

// Set destination directory
val directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
request.setDestinationInExternalPublicDir(directory.toString(), "file_name.extension")

// Get download service and enqueue the request
val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
manager.enqueue(request)
}

In this function, we create a DownloadManager.Request object with the file URL. We then iterate through the provided headers map and add each header to the request using the addRequestHeader method. Next, we set the destination directory for the downloaded file using setDestinationInExternalPublicDir method. Finally, we obtain the DownloadManager service and enqueue the download request using enqueue method.

Step 3: Call the download function

To initiate the file download, call the downloadFile function and provide the file URL and any custom headers you want to set. Here's an example of how you can do this:

val fileUrl = "https://example.com/file_url"
val customHeaders = mapOf("Authorization" to "Bearer token", "User-Agent" to "Android")
downloadFile(fileUrl, customHeaders)

In this example, we provide a sample file URL and a map of custom headers. You can modify the URL and headers according to your requirements.

That's it! You have successfully set custom headers for file downloads using DownloadManager in Kotlin Android. The file will be downloaded to the specified directory with the provided headers.