FloP
07/10/2024, 12:51 PMsuspend fun streamDownload(
httpClient: HttpClient,
call: ApplicationCall,
remoteDownloadUrl: String
) {
try {
httpClient.prepareGet(remoteDownloadUrl).execute { response ->
val channel = response.bodyAsChannel()
call.respondOutputStream(
contentType = ContentType.Application.Zip
) {
try {
while (!channel.isClosedForRead) {
val packet = channel.readRemaining(DEFAULT_BUFFER_SIZE.toLong())
while (!packet.isEmpty) {
val bytes = packet.readBytes()
this.write(bytes)
}
}
} catch (e: Exception) {
println(e)
}
}
}
} catch (e: Exception) {
println(e)
}
}
Aleksei Tirman [JB]
07/10/2024, 3:20 PMApplicationCall.respondBytesWriter
method to get a ByteWriteChannel
and use it for copying the data from the ByteReadChannel
. Here is a simplified code:
suspend fun streamDownload(httpClient: HttpClient, call: ApplicationCall, remoteDownloadUrl: String) {
try {
httpClient.prepareGet(remoteDownloadUrl).execute { response ->
val channel = response.bodyAsChannel()
call.respondBytesWriter(contentType = ContentType.Application.Zip) {
channel.copyTo(this)
}
}
} catch (e: Exception) {
println(e)
}
}
FloP
07/11/2024, 6:06 AMAleksei Tirman [JB]
07/11/2024, 7:09 AMFloP
07/11/2024, 7:10 AMFloP
07/11/2024, 7:19 AMAleksei Tirman [JB]
07/11/2024, 7:21 AMOkHttp
engine instead of the CIO
for the client?FloP
07/11/2024, 7:31 AMFloP
07/11/2024, 8:34 AMsuspend fun streamDownload(
call: ApplicationCall,
remoteDownloadUrl: String
) {
val okHttpClient = OkHttpClient()
val request = Request.Builder()
.url(remoteDownloadUrl)
.build()
okHttpClient.newCall(request).execute().use { response ->
if(!response.isSuccessful) {
println("Request unsuccessful")
return
}
val channel = response.body!!.byteStream().toByteReadChannel()
call.respondBytesWriter(contentType = ContentType.Application.Zip) {
channel.copyTo(this)
}
}
}
Now I see the following exception if client connection is throttled: okhttp3.internal.http2.StreamResetException: stream was reset: CANCEL
Without a throttled connection everything is fine ...FloP
07/11/2024, 8:35 AMAleksei Tirman [JB]
07/11/2024, 10:20 AM