Android WebView 清理指定url 的Cookie

清理App 全局的Cookie 这里就不记录了,主要记录一下清理单个网页的Cookie

    private fun updateCookie(url: String) {
        val cookieManager = CookieManager.getInstance()
        val cookieGlob = cookieManager.getCookie(url);
        if (cookieGlob != null) {
            val cookies = cookieGlob.split(";")
            cookies.map { cookieTuple ->
                val cookieParts = cookieTuple.split("=")
                val domainSet = getDomainSet(url)
                domainSet.map { dm ->
                    cookieManager.setCookie(
                        dm,
                        cookieParts[0] + "=; Expires=Wed, 31 Dec 2015 23:59:59 GMT"  // 这里是把 Cookie 的过期时间更新为过去的时间,如果有需求,这里还需要进行适配一下格式。
                    )
                }
            }
            cookieManager.flush()
        }
    }

    private fun getDomainSet(domain: String): HashSet {
        val domainSet = HashSet()
        val host = Uri.parse(domain).host ?: ""
        if (host.isNotEmpty()) {
            domainSet.add(host)
            domainSet.add(".$host")
            if (host.indexOf(".") != host.lastIndexOf(".")) {
                domainSet.add(host.substring(host.indexOf(".")))
            }
        }
        return domainSet
    }

你可能感兴趣的:(Android WebView 清理指定url 的Cookie)