Android Compose Download And Save File Via OkHttp v4

Jan 6, 2023
fun saveImage(url: String, file: File) {    val client = OkHttpClient()    val request= Request.Builder().url(url).build()    client.newCall(request).execute().use { response ->        if (!response.isSuccessful) throw IOException("Unexpected code $response")        for ((name, value) in response.headers) {            // Timber.d("$name: $value")        }        val source = response.body!!.source()        val sink = file.sink().buffer()        source.use { input ->            sink.use { output ->                output.writeAll(input)            }        }    }}coroutineScope.launch(Dispatchers.IO) {    val file = File.createTempFile(        "${context.getString(R.string.app_name)}_",        ".png",        Environment.getExternalStoragePublicDirectory(            Environment.DIRECTORY_DOWNLOADS        )    )    saveImage(blobUrl, file)    withContext(Dispatchers.Main) {        // showToast("File saved")    }}

References:

❤️ 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.