Is there a way in a ktor client where I can peek t...
# ktor
j
Is there a way in a ktor client where I can peek the response body without consuming it?
HttpResponse.content
is marked as internal, but it is exactly what I need since it is an unconsumed
ByteReadChannel
that lets me use
peekTo
...is there a good reason this is marked as internal and do you think I could use it anyway, or is there something else I could be using instead?
a
You can stream the response body by getting a
ByteReadChannel
to read from.
j
Yes, but if I get the
ByteReadChannel
the body gets consumed. I have a plugin where I want to read the body to respond to certain types or errors, but the response should still get sent out of this plugin. So I am having a problem being able to see a response body both inside and outside of a plugin
e
j
My problem does sound exactly like what the commenter grasseh in there mentioned two months ago. I want to see the response body in my ClientPlugin but if I do, the final response fails to deserialize (because the response is gone)
a
You can split the body's
ByteReadChannel
into two channels to use one of them and return another. Here is an example:
Copy code
val client = HttpClient(CIO)

val scope = CoroutineScope(coroutineContext)
client.responsePipeline.intercept(HttpResponsePipeline.Receive) { (type, body) ->
    if (body !is ByteReadChannel) return@intercept

    val (first, second) = body.split(scope)
    println(first.toByteArray().size) // Consume first here
    proceedWith(HttpResponseContainer(type, second))
}

client.prepareGet("<https://httpbin.org/get>").execute { // Stream the response body
    println(it.bodyAsText())
}
🤔 1
124 Views