Hey guys, how can I achieve this with Ktor? Code ...
# ktor
h
Hey guys, how can I achieve this with Ktor? Code in thread
fun downloadGzipTo( context: Context, dlUrl: String, destinationUri: Uri ) { val url = URL(dlUrl) val urlConnection = url.openConnection() as HttpURLConnection val inputStream = GZIPInputStream(urlConnection.inputStream) val outputStream = context .contentResolver .openOutputStream(destinationUri) ?: throw RuntimeException("Failed to open output stream for Uri: $destinationUri") inputStream.use { it.copyTo(outputStream) } // Clean up resources outputStream.close() }
a
Here is an example of how to stream gzipped response body to the output stream:
Copy code
val client = HttpClient(Android) {
    install(ContentEncoding) {
        gzip()
    }
}
val outputStream = ByteArrayOutputStream() // For example
client.prepareGet("<https://httpbin.org/gzip>").execute { response ->
    val inputStream = response.bodyAsChannel().toInputStream()

    inputStream.use {
        it.copyTo(outputStream)
    }
    // Clean up resources
    outputStream.close()
}
h
Thank you
Is it possible to have this as multiplatform solution or gzip is jvm only?
a
It's possible since the
ContentEncoding
plugin is multiplatform. The only part of the code that needs rewriting is where the
InputStream
and
OutputStream
are used.
h
ContentEncoding
is multiplatform, my question was about
gzip()
, sorry
a
The
gzip()
configuration method is multiplatform too.
thank you color 1
h
How would I go about migrating
InputStream
and
OutputStream
to KMP, sorry i’m new to this and i couldn’t find any documentation online
a
It depends on platforms you want to target.
h
iOS and Android
a
You can implement streaming by writing the implementation using expect and actual declarations. For Android, you can use my example. For iOS, you will need to figure out how to stream the response body (
ByteReadChannel
) to the target destination.
thank you color 1