https://kotlinlang.org logo
#ktor
Title
# ktor
d

Distractic

11/23/2023, 10:28 PM
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

pitonite

11/24/2023, 2:40 AM
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

Sheheryar Umair

11/24/2023, 3:48 AM
So to read the response twice, you just used
response.bodyAsText()
, and it was handled by default?
p

pitonite

11/24/2023, 4:43 AM
yes, with the new version the plugin is automatically enabled, so you can easily consume the body multiple times
🙌 1
d

Distractic

11/24/2023, 8:25 AM
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

pitonite

11/24/2023, 7:57 PM
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

Distractic

11/24/2023, 7:58 PM
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