Skip to content

Instantly share code, notes, and snippets.

@donnfelker
Created October 28, 2023 16:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donnfelker/979563fa7b6f338826bb9c1d87af33e4 to your computer and use it in GitHub Desktop.
Save donnfelker/979563fa7b6f338826bb9c1d87af33e4 to your computer and use it in GitHub Desktop.
OkHttp Cookie Response Interceptor
package com.example.android.http
import android.webkit.CookieManager
import com.example.android.util.BASE_URL // https://example.com/
import logcat.logcat
import okhttp3.Cookie
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.Response
import okio.IOException
/**
* OkHttp interceptor that grabs the cookies off of the response and saves them to the
* cookie manager so that the WebView can utilize the cookies (rails session cookie, etc)
*/
class ReceivedCookiesInterceptor() : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originalResponse: Response = chain.proceed(chain.request())
val cookieManager = CookieManager.getInstance()
val cookies = Cookie.parseAll(BASE_URL.toHttpUrl(), originalResponse.headers)
cookies.forEach { cookie ->
logcat { "Cookie found with name ${cookie.name} , storing in cookie manager ... "}
cookieManager.setCookie(BASE_URL, cookie.toString())
}
return originalResponse
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment