Hey everyone, I'm working on a contribution to th...
# ktor
t
Hey everyone, I'm working on a contribution to the HttpCache plugin for Ktor Client. I want to improve how it handles dropped network connections, which can be common on mobile devices. Right now, if the connection drops while downloading a file, all the bytes that have been downloaded are lost. I've seen that the exception for this is often a
ClosedByteChannelException
. I want to add a feature similar to what Cronet offers, where the plugin can save the partially downloaded file and resume the download using Content-Range. This would only work if the server or CDN supports it. I'm not sure how difficult this task will be. My main question is whether it's possible for a plugin to capture this specific type of error. If anyone has insights on this, I'd appreciate the help!
a
You can try catching the
ClosedByteChannelException
while copying the response body channel. Here is an example:
Copy code
client.receivePipeline.intercept(HttpReceivePipeline.State) { response ->
    val body = response.rawContent
    val newChannel = client.writer {
        try {
            body.copyTo(channel)
        } catch (e: ClosedByteChannelException) {
            println(e)
        }
    }.channel

    val newResponse = object : HttpResponse() {
        override val call: HttpClientCall
            get() = response.call
        override val status: HttpStatusCode
            get() = response.status
        override val version: HttpProtocolVersion
            get() = response.version
        override val requestTime: GMTDate
            get() = response.requestTime
        override val responseTime: GMTDate
            get() = response.responseTime

        @InternalAPI
        override val rawContent: ByteReadChannel
            get() = newChannel
        override val headers: Headers
            get() = response.headers
        override val coroutineContext: CoroutineContext
            get() = response.coroutineContext
    }

    proceedWith(newResponse)
}
thank you color 1