in src/download-file/src.main.kts [57:86]
fun downloadFile(
url: String,
targetFile: File,
authToken: String,
customHeaders: List<String>
) {
HttpClients.createDefault().use { httpClient ->
val httpGet = HttpGet(url)
if (authToken.isNotEmpty()) httpGet.addHeader(HttpHeaders.AUTHORIZATION, "Bearer $authToken")
customHeaders.forEach {
if (!it.contains(":")) {
error("Invalid header format: '$it'. Expected format: 'Header-Name: Value'")
}
val (name, value) = it.split(":", limit = 2).map(String::trim)
httpGet.addHeader(name, value)
}
httpClient.execute(httpGet) { response ->
val statusCode = response.code
if (statusCode !in 200..299) {
error("Failed to download file. HTTP Response: $response")
}
response.entity?.content?.use { inputStream ->
FileOutputStream(targetFile).use { it.write(inputStream.readBytes()) }
}
}
}
}