Intercepting a request using HttpSend (like in <ht...
# ktor
h
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
Could you please describe what do you want to accomplish? What could be a reason to not send a request?
h
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
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
@Aleksei Tirman [JB] takeFromWithExecutionContext() is an internal API but it seem to work with takeFrom(). Is this the same?
a
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
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!
615 Views