Hello, Is there any equivalent in ktor (client) fo...
# ktor
g
Hello, Is there any equivalent in ktor (client) for interceptors? I wish to inject
HttpHeaders.Authorization
in a few requests and I would like to avoid calling
Copy code
header(HttpHeaders.Authorization, "Bearer $accessToken")
for each
HttpRequestBuilder
. Thanks!
l
Yep, what is currently called "features" can do it. I suggest you to check the related class in your IDE, and see the built-in ones that implement it.
👍 2
e
g
Thanks guys 👍
defaultRequest
feature helped!
😁 1
just one more quick question 😊, is it possible to add features to an already created client or it’s only possible upon declaration?
e
I haven't tried that, in case it disallows, there is a workaround to support your use case:
Copy code
defaultRequest{ if(someConditions) { header(...) } }
g
ok I was asking because am providing the client as a singleton (KMM shared module with koin) and maybe I’ve to change a bit my DI since it seams I can’t “add” this feature in runtime (upon declaration I have no accessToken)
make it not singleton I guess it will solve my issue
e
OK, I had a exactly the same use case, you can pass a TokenProvider to the Ktor Client:
Copy code
interface TokenProvider{  fun getToken(): String? }

defaultRequest { if(provider.getToken()!=null) { ... } }
👌 1
(just a dummy code snippet, but should be good to get the point)
g
yup awesome 👍
(btw: it worked 🙂 )
😄 1
r
1.6.0 will have build it Bearer Auth Provider https://youtrack.jetbrains.com/issue/KTOR-331
👌 1
❤️ 2
l
Build it or built-in? 😅
r
built in, sorry my autocomplete =)
😄 1