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

harry248

07/25/2022, 1:31 PM
Intercepting a request using HttpSend (like in https://ktor.io/docs/http-send.html) , what would be the recommended way to prevent the request from being sent. Throwing an exception?
a

Aleksei Tirman [JB]

07/25/2022, 2:09 PM
Could you please describe what do you want to accomplish? What could be a reason to not send a request?
h

harry248

07/26/2022, 3:51 AM
We would like to skip a request if the client already knows that it will get a 401 response (because we persisted the expiration date of the access token) and instead directly do the token refresh call.
a

Aleksei Tirman [JB]

07/26/2022, 7:43 AM
You can modify request builder before sending a request to refresh a token. Here is an example:
Copy code
val client = HttpClient(Apache)

client.plugin(HttpSend).intercept { builder ->
    val newBuilder = HttpRequestBuilder().takeFromWithExecutionContext(builder) // Copy builder with a job

    // modify builder
    newBuilder.url.encodedPath = "/post"
    newBuilder.method = <http://HttpMethod.Post|HttpMethod.Post>

    execute(newBuilder) // Execute request
}

val r = client.get("<https://httpbin.org/get>")
println(r)
👍 1
h

harry248

07/26/2022, 8:02 AM
@Aleksei Tirman [JB] takeFromWithExecutionContext() is an internal API but it seem to work with takeFrom(). Is this the same?
a

Aleksei Tirman [JB]

07/26/2022, 8:03 AM
The
takeFrom
is marked with
InternalAPI
too. You can opt-in for it. The difference is that an execution context isn’t copied with
takeFrom
.
Probably it’s better to use
takeFrom
.
h

harry248

07/26/2022, 8:06 AM
Oh interesting... the IDE isn't complaining with takeFrom().
I see... it already uses the @OptIn annotation. Ok, then I will stick with takeFrom().
Thanks!
456 Views