Android Webview通过设置令牌cookie自动登录到https网站

Vip*_*hah 5 cookies https android ssl-certificate android-webview

我想要实现的是通过将令牌设置为cookie来自动登录到https网站.

(它适用于Android Chrome浏览器,但不适用于应用程序webview)

基本上我在使用cookie设置将https url加载到web视图时面临两个问题

问题1

我收到了以下日志消息.

无法验证证书链,错误:java.security.cert.CertPathValidatorException:找不到证书路径的信任锚.

我尝试重写onReceivedSslError并调用handler.proceed();如下.

@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
    Log.d(TAG, "==> " + error.toString());
    handler.proceed();
}
Run Code Online (Sandbox Code Playgroud)

但我仍然看到白页(由于证书问题,我假设它正在发生.)

问题2

我有一个登录URL(例如https://www.abc.com/login.html)

我想要实现的是通过设置cookie自动登录到Web视图.

CookieSyncManager.createInstance(webView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
CookieManager.getInstance().setAcceptCookie(true);

String token = PreferenceHelper.loadTokenFromPreference(this);

String sessionCookie = "staging=" + token;

cookieManager.setCookie("https://www.abc.com/aaa/",
    sessionCookie);
CookieSyncManager.getInstance().sync();

SystemClock.sleep(1000);
Run Code Online (Sandbox Code Playgroud)

但我仍然无法自动登录.我看到了白页.

我现在不确定的是我犯错误的地方.

cookieManager.setCookie 需要第一个参数作为cookie需要设置的URL,我不确定我需要给哪个URL?

任何人都可以建议我正确的方法让它工作?

谢谢

Abh*_*k V 7

您可以通过cookie里HttpHeaderloadUrl的功能WebView.

HashMap<String, String> map = new HashMap<String, String>();
String token = PreferenceHelper.loadTokenFromPreference(this);
String sessionCookie = "staging=" + token;
map.put("Cookie", sessionCookie);
webView.loadUrl(url, map);
Run Code Online (Sandbox Code Playgroud)


Vip*_*hah 0

好吧,经过一段时间的搜索,我终于找到了解决方案。

我必须添加以下几行才能使其正常工作。

webView.getSettings().setAppCachePath(appCachePath);
webView.getSettings().setAppCacheEnabled(true);
Run Code Online (Sandbox Code Playgroud)

  • “appCachePath”在哪里? (2认同)