Home > front end >  How to pass query parameters to Ktor android
How to pass query parameters to Ktor android

Time:03-20

for fun return like :

fun call_api(){  
  client.get {
                url("url")
                parameter("1stParam", "2ndParam")
    
            }
}

where client is HttpClient

in code how to call it callapi() ??

CodePudding user response:

client.get() returns an HttpResponse, which you can return from your function or keep in a variable

suspend fun getResponse(): HttpResponse {
     return client.get {
                    url("url")
                    parameter("key", "value")
            }
}

or

val response = client.get {
                        url("url")
                        parameter("key", "value")
                }

You can call either of the above, whichever you've used, inside a coroutine

fun callApi() = viewModelScope.launch {
    val data = getResponse().body<ClassNameToBeDeserializedTo>()
    // data contains your deserialized object
}
  • Related