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

jean

06/10/2020, 6:44 PM
After a quick search on this channel and the web, it looks like to me there is no convenient way of setting a base url value? I saw people suggested to use this
Copy code
HttpClient(CIO) {
        defaultRequest {
            url {
                host = "<https://my.host.com>"
                port = 443
            }
        }
        install(JsonFeature) {
            serializer = GsonSerializer()
        }
    }
I does not work when I try to use it with
client.get<ApiResponse<Character>>("/endpoint")
Am I doing anything wrong?
I ended up creating this
Copy code
private suspend fun get(path: String, parameters: Map<String, String>): SomeType {
        return client.get(
            scheme = "https",
            host = "<http://my.host.com|my.host.com>",
            port = 8080,
            path = path
        ) { addParameters(parameters) }
    }
and call it like
get("my/path", parameters)
n

Nicolas Chevalier

06/11/2020, 1:42 PM
You can do
Copy code
protected fun HttpRequestBuilder.apiUrl(path: String) {
        url {
            takeFrom(baseUrl)
            encodedPath = path
        }
    }
and use it like this:
Copy code
val response: HttpResponse = <http://client.post|client.post> {
            apiUrl(path)
            addParameters(parameters)
        }
this allow you to have this on every http method (get, post, …)
j

jean

06/12/2020, 10:26 AM
right, I’ll try that, thanks 🙂
😉 1
2 Views