Hello everyone ! I need to read the body of the ...
# ktor
d
Hello everyone ! I need to read the body of the response twice. One in HttpValidator One to parse the response https://ktor.io/docs/double-receive.html is dedicated to the server side, however, I'm using ktor as client and not server So, when I execute the function
response.bodyAsText()
, the first time, I have a non empty string, but the second time, the value is empty Is it possible to fix that ? Thanks in advance
p
Hi this is handled by default in ktor 3.0.0, which is not released yet, but you can use the latest eap versions: https://mvnrepository.com/artifact/io.ktor/ktor-client-core?repo=space-public-ktor-eap
s
So to read the response twice, you just used
response.bodyAsText()
, and it was handled by default?
p
yes, with the new version the plugin is automatically enabled, so you can easily consume the body multiple times
🙌 1
d
Nice ! Based on a memory cache if the response body is already read I will try it during the day and give you a feedback
Hum .. No I always have the same behavior
image.png
image.png
Copy code
HttpResponseValidator {
                validateResponse { response ->
                    if (!response.status.isSuccess()) {
                        // First read here and is not empty
                        val text = response.bodyAsText()
                        if (text.isEmpty()) {
                            return@validateResponse
                        }

                        val jsonBody = json.parseToJsonElement(text).jsonObject
                        val errors = findErrorFromBody(jsonBody)
                        if (errors != null) {
                            throw MyException(errors)
                        }
                    }
                }
            }
Copy code
val response = client.get {
            url(myurl)
        }
// Second read here and is empty
val text = response.bodyAsText()
p
There is a bug with Logger consuming response before the plugin can work, please check your logging level not to be "ALL", as it will cause the body to be consumed and fail
❤️ 1
d
Ok currently it's ALL, so I will check with another level
👍 1
Ah yes that works now with INFO log level Strange bug but ok I hope that will be fixed