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

Jeff Tycz

02/12/2021, 1:45 AM
I am trying to make a generic http client class with single get/post/put methods that can be used anywhere in my application without having to write a specific http call method for every case. One issue I am coming up with is some calls require different headers to be sent in the request. This is the method I am currently trying to change, I set the auth header but sometimes I need additional headers and sometimes I dont need the auth header at all
Copy code
suspend inline fun <reified T> post(authKey: String, url: String, data: Any): T? {
    val response = <http://_client.post|_client.post><HttpResponse>(url) {
        header("Authorization", "Bearer $authKey")
        contentType(ContentType.Application.Json)
        body = data
    }

    when (response.status.value) {
        in 300..399 -> throw RedirectResponseException(response)
        in 400..499 -> throw ClientRequestException(response)
        in 500..599 -> throw ServerResponseException(response)
    }

    if (response.status.value >= 600) {
        throw ResponseException(response)
    }

    return response.receive<T>()
}
Is there a way to dynamically set the headers?
t

tateisu

02/12/2021, 5:24 AM
Copy code
private suspend inline fun <reified T> post(
   authKey: String, 
   url: String, 
   data: Any,
   extraBuilder:HttpRequestBuilder.()->Unit ={}): T? {
   val response = <http://_client.post|_client.post><HttpResponse>(url) {
      header("Authorization", "Bearer $authKey")
      contentType(ContentType.Application.Json)
      body = data
      extraBuilder()
   }
you can add argument that is lambda and that has default value.
in this example extraBuilder has signiture
Copy code
HttpRequestBuilder.() -> Unit = {}
that is same to client.post() 's
block
argument.
4 Views