You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需重启应用,如何修改Android WebView代理认证凭据?

WebView代理HTTP认证凭据更新后不生效的解决方案

问题背景

通过ProxyController为WebView设置代理,并重写WebViewClient的onReceivedHttpAuthRequest()方法提交代理认证凭据,初始运行正常。但修改凭据后,即使WebViewDatabase已更新为新凭据,代理仍使用旧凭据,且onReceivedHttpAuthRequest()仅在每次应用启动时调用一次。

核心原因

  1. onReceivedHttpAuthRequest()仅在首次需要代理认证时触发,WebView会缓存已提交的凭据,后续请求不再触发该方法
  2. 原实现直接使用固定变量提交凭据,未从WebViewDatabase读取最新值,修改凭据后变量未同步更新
  3. 仅清除WebViewDatabase和常规缓存无法重置WebView底层的代理认证缓存

解决方案

1. 动态读取最新凭据

修改onReceivedHttpAuthRequest()方法,每次触发时从WebViewDatabase读取最新的代理凭据,避免依赖固定变量:

override fun onReceivedHttpAuthRequest(view: WebView?, handler: HttpAuthHandler?, host: String?, realm: String?) {
    if (host == proxyHost) {
        val webDB = WebViewDatabase.getInstance(view?.context)
        // 从数据库读取最新凭据
        val credentials = webDB.getHttpAuthUsernamePassword(proxyHost, proxyRealm)
        credentials?.let { (username, password) ->
            handler?.proceed(username, password)
        } ?: handler?.cancel()
    } else {
        handler?.cancel()
    }
}

2. 更新凭据后强制重置认证状态

修改凭据时,除了更新WebViewDatabase,还需要重新设置代理并触发页面重载,强制WebView重新发起认证请求:

// 清除目标代理的旧凭据,而非全部凭据
val webDB = WebViewDatabase.getInstance(webView.context)
webDB.removeHttpAuthUsernamePassword(proxyHost, proxyRealm)
webDB.setHttpAuthUsernamePassword(proxyHost, proxyRealm, proxyNewUsername, proxyNewPassword)

// 重新设置代理,重置底层认证缓存
val proxyConfig = Builder().addProxyRule("$proxyHost:$proxyPort").addDirect().build()
ProxyController.getInstance().setProxyOverride(proxyConfig, {}, {})

// 重载当前页面,触发重新认证流程
webView.stopLoading()
webView.loadUrl(webView.url)

3. 额外清理措施(可选)

如果上述方法仍不生效,可补充清理WebView的缓存和历史记录:

// 清理WebView缓存
webView.settings.clearCache(true)
// 清理WebView历史
webView.clearHistory()
// 清理Cookie
CookieManager.getInstance().removeAllCookies(null)
CookieManager.getInstance().flush()

内容的提问来源于stack exchange,提问作者Simba Adeeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 10:35:29