Android Download File Using OkHttp

June 19, 2018
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) {

    }
})
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.