Hi. How can I write a CLIENT PLUGIN that can read ...
# ktor
j
Hi. How can I write a CLIENT PLUGIN that can read response body twice? I need the normal functionality, like
val dummies : List<Dummy> = client.get().body()
but I also need the body as text (before any deserialization) for auditing purposes. The best solution I found is using the ResponseObserver and inside reading
response.content.readRemaining().readText(…)
but it uses InternalApi that I need to OptIn, hardly a civilised solution Also I’d prefer to do the same in Plugin instead of ResponseObserver…
a
You can, but the double body receiving works only since Ktor 3.0.0 (
3.0.0-eap-800
). Here is an example:
Copy code
val plug = createClientPlugin("myplug") {
    onResponse { response ->
        println("Response body: ${response.bodyAsText()}")
    }
}

suspend fun main() {
    val client = HttpClient(OkHttp) {
        install(plug)
        install(ContentNegotiation) {
            json(Json {
                ignoreUnknownKeys = true
            })
        }
    }

    val response = <http://client.post|client.post>("<https://httpbin.org/post>").body<HttpBin>()
    println(response.origin)
}

@Serializable
data class HttpBin(val origin: String)
j
That’s great to know, thanks!