惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
A
About on SuperTechFans
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
aimingoo的专栏
aimingoo的专栏
云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
Vercel News
Vercel News
G
Google Developers Blog
J
Java Code Geeks
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
Cloudbric
Cloudbric
L
LINUX DO - 最新话题
MyScale Blog
MyScale Blog
H
Heimdal Security Blog
PCI Perspectives
PCI Perspectives
Attack and Defense Labs
Attack and Defense Labs
S
Security @ Cisco Blogs
Latest news
Latest news
I
Intezer
L
Lohrmann on Cybersecurity
C
CXSECURITY Database RSS Feed - CXSecurity.com
月光博客
月光博客
T
Threatpost
博客园 - 【当耐特】
S
Schneier on Security
P
Privacy International News Feed
G
GRAHAM CLULEY
T
Tenable Blog
AWS News Blog
AWS News Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
雷峰网
雷峰网
博客园 - Franky
Engineering at Meta
Engineering at Meta
美团技术团队
S
Secure Thoughts
T
Troy Hunt's Blog
Microsoft Security Blog
Microsoft Security Blog
SecWiki News
SecWiki News
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cisco Talos Blog
Cisco Talos Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Martin Fowler
Martin Fowler
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
H
Hackread – Cybersecurity News, Data Breaches, AI and More

WMI

How to Activate MySQL for Multiple Devices - WMI ESLint Flat Config for JS, TS, React, and Prettier - WMI Yarn NPM Registry Configuration - WMI Yarn Guides - WMI Set Up ADB Wireless Debugging on Android: A Full Guide - WMI How to Fill Tax Information on Google Adsense - WMI Migrate ESLint v9 for prettier typescript javascript - WMI PySide6 button click open new window - WMI PySide6 autocomplete input text - WMI Mobile Legends To The Stars Event Clue - WMI [PHP] generate random proxy IP:PORT from CIDR - WMI [PHP] generate big text file for testing purpose - WMI List of Chrome Driver command line arguments - WMI Happy eid mubarak - WMI Install markdown engine on vite ESM typescript - WMI Android Activity lifecycle - WMI Turn git log history into markdown - WMI enable automatic memory heap resizing of android studio - WMI is defining screen density can reduce build time ? - WMI
OkHttp cookie handling on android (webview supported) - WMI
Dimas Lanjaka · 2024-03-17 · via WMI

Here how i implement cookie handling for android lollipop - tiramisu and also jvm and non-persistent connection.

requires:

[versions]
webkit = "1.10.0"
okhttp = "4.12.0"

[libraries]
webkit = { module = "androidx.webkit:webkit", version.ref = "webkit" }
okhttp = { module = "com.squareup.okhttp3:okhttp-bom", version.ref = "okhttp" }
okhttp-lib = { module = "com.squareup.okhttp3:okhttp" }
implementation libs.webkit
implementation platform(libs.okhttp)
implementation libs.okhttp.lib

create WebkitCookieManager.kt

import android.content.Context
import android.webkit.WebView
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import java.net.CookieHandler
import java.net.CookiePolicy
import java.net.HttpCookie


/**
 * android webkit webview cookie manager.
 * [FULL USAGES](https://dimaslanjaka.github.io/2024/03/okhttp-cookie-handling-on-android.html)
 *
 * @author Dimas Lanjaka <a href="https://www.webmanajemen.com">https://www.webmanajemen.com</a>
 */
open class WebkitCookieManager : CookieJar {
    /**
     * support for below android 10
     */
    private var webkitCookieManager: android.webkit.CookieManager? = null

    /**
     * support for jvm or android 10+
     */
    private var javaCookieManager: java.net.CookieManager? = null

    /**
     * support for webview intercept connection cookie handling
     */
    private var webview: WebView? = null

    /**
     * the android context for clearing cookies on non-webview instance
     */
    private var context: Context? = null

    /**
     * for non-persistent cookies
     */
    private val cookieStore = mutableMapOf<HttpUrl, List<Cookie>>()

    /**
     * construct android cookie manager without webview
     */
    constructor(manager: android.webkit.CookieManager, ctx: Context? = null) {
        webkitCookieManager = manager
        setupAndroidCookieManager()
        this.context = ctx
    }

    /**
     * construct android cookie manager with webview
     */
    constructor(manager: android.webkit.CookieManager, webView: WebView, ctx: Context? = null) {
        webkitCookieManager = manager
        setupAndroidCookieManager(webView)
        this.webview = webView
        this.context = ctx
    }

    /**
     * construct non-persistent cookie manager
     */
    constructor(ctx: Context? = null) {
        this.context = ctx
    }

    /**
     * construct java cookie manager
     */
    constructor(manager: java.net.CookieManager, ctx: Context? = null) {
        manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
        javaCookieManager = manager
        CookieHandler.setDefault(javaCookieManager)
        this.context = ctx
    }

    /**
     * make android webkit cookie manager accept third-party cookies
     */
    private fun setupAndroidCookieManager(webView: WebView? = null) {
        webkitCookieManager?.setAcceptCookie(true);
        if (webView != null) webkitCookieManager?.setAcceptThirdPartyCookies(webView, true);
    }

    /**
     * save cookies after request finished
     */
    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        cookies.forEach { cookie ->
            webkitCookieManager?.setCookie(url.toString(), cookie.toString())
            javaCookieManager?.cookieStore?.add(url.toUri(), HttpCookie.parse(cookie.toString())[0])
        }
        cookieStore.put(url, cookies);
    }

    /**
     * load cookies before okhttp execute request {@link okhttp3.OkHttpClient#newCall(request)}
     */
    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        return if (webkitCookieManager != null) {
            // get from android webkit cookie manager
            when (val cookies = webkitCookieManager?.getCookie(url.toString())) {
                null -> emptyList()
                else -> cookies.split("; ").mapNotNull { Cookie.parse(url, it) }
            }
        } else if (javaCookieManager != null) {
            // get from java cookie manager
            when (val cookies = javaCookieManager?.cookieStore?.cookies) {
                null -> emptyList()
                else -> cookies.toString().split("; ").mapNotNull { Cookie.parse(url, it) }
            }
        } else {
            // get from non-persisten cookie store
            val cookies = cookieStore[url]
            return cookies ?: ArrayList()
        }
    }

    /**
     * clear all stored cookies everywhere
     */
    fun clearCookies() {
        // remove non-persistent stored cookies
        cookieStore.clear()
        // initialize android webkit cookie manager on null
        if (webkitCookieManager == null) {
            webkitCookieManager = android.webkit.CookieManager.getInstance()
            setupAndroidCookieManager()
        }
        // indicator when webview not initialized
        var standaloneWebview = false
        // initalize fake webview instance
        if (webview == null && context != null) {
            // declare standalone webview
            webview = WebView(context!!)
            // treat as standalone webview
            standaloneWebview = true
        }
        // remove all stored cookies from android webkit cookie manager
        webkitCookieManager?.removeAllCookies(null)
        webkitCookieManager?.flush()
        webkitCookieManager?.removeSessionCookies(null);
        // clear all caches from webview
        webview?.clearCache(true)
        webview?.clearHistory()
        webview?.clearFormData();
        webview?.clearSslPreferences();
        if (standaloneWebview) {
            // destroy standalone webview
            webview?.destroy()
            webview = null
        }
        // initialize java cookie manager
        if (javaCookieManager == null) {
            javaCookieManager = java.net.CookieManager(null, CookiePolicy.ACCEPT_ALL)
            java.net.CookieHandler.setDefault(javaCookieManager)
        }
        // remove all stored cookies from java cookie manager
        javaCookieManager?.cookieStore?.removeAll()
    }
}

my usage within view binding webview + custom webviewclient intercept using okhttp

val clientBuilder = OkHttpClient.Builder()
clientBuilder.cookieJar(WebkitCookieManager(CookieManager.getInstance(), binding!!webview, applicationContext))

![declaration of okhttp][okhttp-cookie-handling-on-android/1AcJt.png]

![on intercept section create connection][okhttp-cookie-handling-on-android/EgV2P.png]

this work and tested, when i clear cookies the value of cookies on website changed, otherwise all same until expiration date of cookie.