Is there a way to define a base URL in HttpClient ...
# ktor
t
Is there a way to define a base URL in HttpClient ? By "base URL" I mean that all requests are based on it, for example : with
baseUrl
= "https://foo.host.com/api/v1" when calling
httpClient.get("endpoint")
, then the resolved URL is
<https://foo.host.com/api/v1/endpoint>
.
e
The easiest way might be to add an extension function on the HTTP client which invokes get() but prefixes the path with the base URL that you want
👍 1
If you want to do it a more complictaed way you might need to come up with your own “base URL” feature and install it to the client
r
It’s not quite the syntax you want, but you can make your other requests
httpClient.get { url { encodedPath = "endpoint" } }
👍 1
t
I found that I could archive something close to what I want with the DefaultRequest feature :
Copy code
val client = HttpClient(OkHttp) {
    defaultRequest {
        url {
            protocol = URLProtocol.HTTPS
            host = "<http://foo.host.com|foo.host.com>"
        }
    }
}

client.get<HttpResponse>(path = "api/v1/endpoint")
With that I can at least specify a common host. Would be nice to have something similar to Retrofit's
baseUrl
though. I'll consider writing a feature for that.
334 Views