如何在Android WebView客户端中设置Cookie [英] How to set cookie in android WebView client

查看:194
本文介绍了如何在Android WebView客户端中设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 WebView 调用一个特定的网址。该页面只能在用户已经登录后才能调用。我使用 AsyncHttpClient 库执行登录调用。成功登录后,通过 WebView 加载url似乎无法识别正确的标题esp cookie。我怀疑是 HttpClient WebView的HttpClient 之间的cookie无法正确同步。知道为什么吗? 。这是我使用 WebView

I want to call one specific url via WebView. The page can only be called after user already logged in. I use AsyncHttpClient library to perform login call. Once after successfully logged in , loading url via WebView doesn't seem recognise the proper headers esp cookie. My suspect is that cookies are not sync correctly between HttpClient and WebView's HttpClient . Any idea why ? . Here is how i use WebView

    final WebView webView = (WebView) content.findViewById(R.id.web_travel_advisory);
    String url = "http://mydomainurl.com/get_data_after_login";

    webView.setWebViewClient(new WebViewClient());

    CookieSyncManager.createInstance(getActivity());
    CookieSyncManager.getInstance().startSync();
    CookieManager.getInstance().setAcceptCookie(true);

    webView.getSettings().setJavaScriptEnabled(true);

    webView.loadUrl(url);

感谢您的帮助。

推荐答案

哦,几个小时后,我终于弄清楚了它可以正常工作。首先,在更高版本的android上不推荐使用 CookieSyncManager 从api 21开始。因此决定不再使用它。其次, CookieManager 用于存储 WebView 的cookie。

Ohh after several hours, i finally figured it out to get it worked. Firstly CookieSyncManager is deprecated on later version of android since api 21 according to doc. So decided not to use it anymore. Secondly CookieManager is used to store cookie for WebView.

最终代码

    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);

    List<Cookie> cookies = WSHelper.cookieStore.getCookies();

    cookieManager.removeAllCookie();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().contains("session")){
                String cookieString = cookie.getName() + "=" + cookie.getValue() + "; Domain=" + cookie.getDomain();
                cookieManager.setCookie(cookie.getDomain(), cookieString);
                Log.d("CookieUrl",cookieString + " ");
            }
        }
    }
    webView.loadUrl(url);

解决方案的主要变化是:使用 cookie.getDomain()代替

The key changes to solution is: use cookie.getDomain() instead of explicit domain.

cookieManager.setCookie(cookie.getDomain(), cookieString);

这篇关于如何在Android WebView客户端中设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆