Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit2: how to save cookies from response

I need to add some authorization information from cookie in response to next requests.

It works in postman - I make authorization request, then second request, which works fine. But if I delete cookies - second request returns error and I have to do authorization request again.

But in my application this second request always returns the same error. I tried to find needed cookie by using interceptor, but I hadn't found it

val client = OkHttpClient.Builder()
    .addInterceptor(OAuthInterceptor())

private class OAuthInterceptor : Interceptor {
    override fun intercept(chain: Chain): Response {
        val request = chain.request()
        com.app.logic.toLog("${chain.proceed(request).header("set-cookie")} ") // it's not that cookie what I looking for
        val headers = chain.proceed(request).headers()
        headers.names().forEach {
            val s = headers.get(it)
            com.app.logic.toLog("$it -> $s")
        }
        return chain + (Session.authConsumer?.let { consumer ->
            consumer.sign(request).unwrap() as Request
        } ?: request)
    }
}

Does anybody know what else could I try?

like image 716
Andrey Turkovsky Avatar asked Oct 27 '25 01:10

Andrey Turkovsky


2 Answers

So, finally I've found solution for working with cookies

val client = OkHttpClient.Builder()
    .cookieJar(UvCookieJar())

private class UvCookieJar : CookieJar {

    private val cookies = mutableListOf<Cookie>()

    override fun saveFromResponse(url: HttpUrl, cookieList: List<Cookie>) {
        cookies.clear()
        cookies.addAll(cookieList)
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> =
        cookies
}
like image 159
Andrey Turkovsky Avatar answered Oct 28 '25 17:10

Andrey Turkovsky


You can use this this gist on how to intercept cookies when you receive them and send them back in your request in header.

like image 23
karandeep singh Avatar answered Oct 28 '25 16:10

karandeep singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!