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

Distractic

11/05/2023, 10:19 AM
Hello everyone ! I have a problem adding path to my request with my ktor client. This is my code:
Copy code
// Definition of my client
val client = HttpClient {
 ...
  defaultRequest {
    url {
        takeFrom("<http://localhost:8080>")
        appendPathSegments("v1")
    }
   }
}

// Example of request
<http://client.post|client.post> {
  url {
    appendPathSegments("test", "test2)
  }
}
With this code, the client will request:
<http://localhost:8080/test/test2>
and not
<http://localhost:8080/v1/test/test2>
However, if in the client definition, instead of
v1
I put
/v1/
, the client will request
<http://localhost:8080/v1/test/test2>
as expected Do you know why I have this behavior and how to fix it ?
m

MV

11/05/2023, 10:47 AM
If your basepath ends with / and your request starts with no slash it will append it else if your request starts with a slash it will start from the host. If your basepath does not end with a slash it will always start every request from the host. e.g: base.com/v1 , start -> base.com/start base.com/v1/ , start -> base.com/v1/start base.com/v1/ , /start -> base.com/start
It's pretty nifty feature, I don't think its documented very well could not find any documentation at a quick glance, but I ran into this problem too and became aware of it somewhere in a SO thread
d

Distractic

11/05/2023, 10:54 AM
So in my code, how can I define the basePath always as
Copy code
<http://localhost:8080/v1>
for all requests ? (instead of put
/v1/
in add path)
m

MV

11/05/2023, 10:56 AM
Copy code
defaultRequest {
        url("<http://localhost:8080/v1/>" )
    }
No you need the trailling slash
d

Distractic

11/05/2023, 10:57 AM
hum ok I will try
Thanks that works 🙂
3 Views