Home > Enterprise >  Ktor how to get http code from request without body
Ktor how to get http code from request without body

Time:03-30

I make a request to the server, but there is no body in the response. Accordingly, the return value type of response is Unit.

    suspend fun foo(
        url: String,
        id: Long
    ) {
        val requestUrl = "$url/Subscriptions?id=${id}"
        val response = httpApiClient.delete<Unit>(requestUrl) {
            headers {
                append(HttpHeaders.Authorization, createRequestToken(token))
            }
        }
       return response
    }

How in this case to receive the code of the executed request?

            HttpResponseValidator {
                validateResponse { response ->
                    TODO()
                }
            }

using a similar construction and throwing an error, for example, is not an option, since one http client is used for several requests, and making a new http client for one request is strange. is there any other way out?

CodePudding user response:

You can specify the HttpResponse type as a type argument instead of Unit to get an object that allows you to access the status property (HTTP status code), headers, to receive the body of a response, etc. Here is an example:

import io.ktor.client.HttpClient
import io.ktor.client.engine.apache.*
import io.ktor.client.request.*
import io.ktor.client.statement.*

suspend fun main() {
    val client = HttpClient(Apache)
    val response = client.get<HttpResponse>("https://httpbin.org/get")
    // the response body isn't received yet
    println(response.status)
}
  • Related