https://kotlinlang.org logo
Title
g

Guilherme Delgado

05/22/2021, 5:11 PM
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
header(HttpHeaders.Authorization, "Bearer $accessToken")
for each
HttpRequestBuilder
. Thanks!
l

louiscad

05/22/2021, 10:43 PM
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

El Zhang

05/23/2021, 7:08 AM
g

Guilherme Delgado

05/23/2021, 11:27 AM
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

El Zhang

05/23/2021, 11:37 AM
I haven't tried that, in case it disallows, there is a workaround to support your use case:
defaultRequest{ if(someConditions) { header(...) } }
g

Guilherme Delgado

05/23/2021, 11:39 AM
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

El Zhang

05/23/2021, 11:43 AM
OK, I had a exactly the same use case, you can pass a TokenProvider to the Ktor Client:
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

Guilherme Delgado

05/23/2021, 11:48 AM
yup awesome 👍
(btw: it worked 🙂 )
😄 1
r

Rustam Siniukov

05/24/2021, 11:29 AM
1.6.0 will have build it Bearer Auth Provider https://youtrack.jetbrains.com/issue/KTOR-331
:nice: 1
❤️ 2
l

louiscad

05/24/2021, 1:04 PM
Build it or built-in? 😅
r

Rustam Siniukov

05/24/2021, 1:30 PM
built in, sorry my autocomplete =)
😄 1