Issue
I have a singleton (object
in Kotlin) that holds an instance of OkHttpClient
which as per the search on stack is the way to go.
Now I come to the scenario where for just ONE request in my app I need to skip the redirect to get the Location
header.
It seems that the way to do it is via
val client = OkHttpClient.Builder()
.followRedirects(false)
.followSslRedirects(false)
.build()
This is fine and dandy, but now I need to store two instances of OkHttpClient
and the non-redirecting one is not even to be always used coz it pertains to a login flow for my app only.
Is it possible (e.g. via writing a network interceptor maybe?) to disable redirect for just ONE request?
Solution
Per the docs, you should use one main instance, and then build customizations off of that base instance.
// renamed solely to make it clear what's going on below
val commonClient = OkHttpClient.Builder()
.followRedirects(true) // you can skip these calls, they are true by default
.followSslRedirects(true)
.build()
Then later on, in your "do login" function, you'd create a fork of the base client. Under the hood, everything will still use commonClient
but any requests made using this "new" client will use the settings you overrode. It's just a bit of an odd, roundabout syntax.
// fork the base instance
val noRedirectClient = commonClient.newBuilder()
.followRedirects(false) // override the previous/default settings used by commonClient
.followSslRedirects(false)
.build()
// make your request(s)
// don't shutdown noRedirectClient, because it would also shutdown the
// underlying commonClient instance because they share resources
Answered By - samthecodingman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.