Hi. Is there a way for Ktor client to interrupt wh...
# ktor
m
Hi. Is there a way for Ktor client to interrupt while downloading the response if it get too large? I have try to take a look at custom plugin and
onDwonload
hook but it seems didn’t help. The
response.bodyAsChannel()
seems to be returning the whole response (buffered into memory?) before I can check and consume it. I want to cut the underlying HTTP call early if the response size is too large.
The
BodyProgress
plugin behind
onDownload
only allow me to put listener on the download content size but did not allow me to cancel the
Job
a
You can create an instance of
HttpRequestBuilder
manually to be able to refer to its
executionContext
property which you can use to cancel a job. Here is an example:
Copy code
suspend fun main(): Unit = runBlocking {
    val client = HttpClient(Apache)

    val builder = HttpRequestBuilder().apply {
        url("<http://127.0.0.1:3333>")
        onDownload { bytesSentTotal, contentLength ->
            // executionContext.cancel() will work too
            println("Received $bytesSentTotal bytes from $contentLength")
        }
    }

    launch {
        delay(200)
        builder.executionContext.cancel()
    }

    client.get(builder)
}
m
Copy code
onDownload { bytesSentTotal, contentLength ->
  executionContext.cancel()
}
It work perfectly! Thx ❤️