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

Distractic

11/21/2023, 9:47 PM
Hi ! I would like to know how can I check if there is a response body before reading it For example, from an API, I have this response:
Copy code
COMMON HEADERS
-> Cache-Control: no-store
-> Content-Length: 0
-> Content-Type: application/json
-> Date: Tue, 21 Nov 2023 21:40:39 GMT
-> Strict-Transport-Security: max-age=31536000; includeSubDomains
BODY Content-Type: application/json
BODY START

BODY END
The body is empty, so when I try to read it, my code throws an exception and I would like to avoid that. Do you know how can I check if the response has a body or not ?
1
b

Berkay Özkan

11/21/2023, 9:49 PM
Maybe you can check
Copy code
call.receiveNullable
d

Distractic

11/21/2023, 9:51 PM
I'm using Ktor as a client and not server. Also, I'm using a HttpResponseValidator
Copy code
HttpResponseValidator {
                validateResponse { response ->
                    if (!response.status.isSuccess()) {
                        // Get body here
                    }
                }
            }
A try catch works of course, but I don't know if there is a better approach
b

Berkay Özkan

11/21/2023, 10:06 PM
Oh sorry i read as request. is response always null? or depends on condition status code etc
m

MV

11/21/2023, 10:08 PM
capture your response in a Result and check the result example
Copy code
suspend fun getNodeInfo(instance: String): Result<NodeInfo> = runCatching {
        lenientKtor
            .get("${constructBaseUrl(instance)}/nodeinfo/2.0.json")
            .body<NodeInfo>()
    }

suspend fun someOther(){
   val node = getNodeInfo(instance)
   if(node.isSuccess) { ... }
}
d

Distractic

11/21/2023, 10:18 PM
The response is arbitrary. With always a different format so that's a bit annoying Well according to the MV response, I'm supposing that Result / try catch is the only solution
m

MV

11/21/2023, 10:24 PM
It certianly isnt the only solution
With always a different format so that's a bit annoying
what do you mean with that? Do you mean you always get unkown json structure? You can read the body as a generic JsonObject and parse that
d

Distractic

11/22/2023, 6:24 AM
Exactly, for the moment, I detected three type of response body: • Nothing (my current question) •
Copy code
{data:{error: <message>}}
Copy code
{errors: [list of message]}
a

Aleksei Tirman [JB]

11/22/2023, 9:12 AM
Unfortunately, you cannot determine whether response empty or not without reading it.
d

Distractic

11/22/2023, 9:15 AM
I'm agree with that, but in this case, maybe the
bodyAsText
should returns empty string instead of throw an illegalStateException 🤔
a

Aleksei Tirman [JB]

11/22/2023, 9:16 AM
Can you share the exception message and stack trace?
d

Distractic

11/22/2023, 9:17 AM
OK I will send that during the day 👍
Aaah no .. finally I have an empty string .. Well I don't know why yesterday I had an IllegalState