7

I am trying out Ktor by converting some existing project that's currently using Retrofit.

Although I could easily convert the request into something like:

client.get {
    url("$BASE_URL/something/somepage/another")
}

It seems very tedious to always add the $BASE_URL to all paths every time. In retrofit, we could simply do something like:

Retrofit.Builder()
    .baseUrl(BASE_URL)
    .create(SomeServiceClass::class.java)

I've triede using defaultRequest and setting the BASE_URL there but apparently you could only set the url.host and not the whole basePath.

Is there a way to do the same thing in Ktor? or if there is none, what's the best practice to handle this?

Archie G. Quiñones
  • 11,638
  • 18
  • 65
  • 107

2 Answers2

20

You can!

In order to do so you need to set your default request when you instantiate your client.

val httpClient = HttpClient(Android) {
        defaultRequest {
            host = "my.zoo.com"
            url {
                protocol = URLProtocol.HTTPS
            }
        }
    }

val response = httpClient.get<List<CatsResponse>>(
        path = "animals/cats"
)

This will call https://my.zoo.com/animals/cats

Hope it helps :)

Camarero
  • 652
  • 4
  • 9
  • I see. This just confirms that you can't set a base path but could set a base url instead. Can I ask another question about ktor? maybe you could help me out. By any means do you know how to set SSL in Ktor? – Archie G. Quiñones Mar 03 '20 at 02:41
  • 1
    In the default request you can provide anything you would in your request builder `HttpRequestBuilder`. Check out the class to see all the options. defaultRequest { host = "animals.zoo.com" url { protocol = URLProtocol.HTTPS //Set scheme to https. } } – Camarero Mar 03 '20 at 06:33
3

From official docs

DefaultRequest allows you to configure a base part of the URL that is merged with a request URL.

defaultRequest {
    url("https://ktor.io/docs/")
}

If you make the following request using the client with the above configuration, ...

val response: HttpResponse = client.get("welcome.html")

... the resulting URL will be the following: https://ktor.io/docs/welcome.html

iamanbansal
  • 2,412
  • 2
  • 12
  • 20