Android Download File Using OkHttp

fun downloadFile(url: String, dir: File, name: String?, fileExt: String?): File {    val client = OkHttpClient()    val request = Request.Builder().url(url).build()    val response = client.newCall(request).execute()    val contentType = response.header("content-type", null)    var ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(contentType)    ext = if (ext == null) {        fileExt    } else {        ".$ext"    }    // use provided name or generate a temp file    var file: File? = null    file = if (name != null) {        val filename = String.format("%s%s", name, ext)        File(dir.absolutePath, filename)    } else {        val timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-kkmmss"))        File.createTempFile(timestamp, ext, dir)    }    val body = response.body()    val sink = Okio.buffer(Okio.sink(file))    /*    sink.writeAll(body!!.source())    sink.close()    body.close()     */    body?.source().use { input ->        sink.use { output ->            output.writeAll(input)        }    }    return file}

The above method is blocking, so kotlin-couroutines is used (or you can use any threading library).

launch {    try {        val file = downloadFile("https://www.travelopy.com/static/img/cover.jpg", context.cacheDir, null, null)    }    catch (e: IOException) {      }}

If you perfer callback.

client.newCall(request).enqueue(object : Callback {    override fun onFailure(call: Call, e: IOException) {    }    @Throws(IOException::class)    override fun onResponse(call: Call, response: Response) {    }})

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.