Webview cannot accept cookies

前端 未结 5 1750
醉话见心
醉话见心 2020-12-10 12:43

I\'m creating a WebView based Android app that enables the user to login onto a mobile operator. When I run the app the WebView opens the website but I get a message that th

相关标签:
5条回答
  • 2020-12-10 13:17

    Have you checked Android documentation ?

    If you are using API level >= 21, WebView automatically syncs cookies.

    If not try this:

        final CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
        final CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        cookieManager.setAcceptCookie(true);
        String[] cookies = getCookie(cookieManager, "https://myaccount.ee.co.uk/login-dispatch/?fa=register");
        for (String cookie : cookies) {
            cookieManager.setCookie("https://myaccount.ee.co.uk/login-dispatch/?fa=register", cookie);
        }
        cookieSyncManager.sync();
        webView.loadUrl("https://myaccount.ee.co.uk/login-dispatch/?fa=register");
    

    getCookies:

      public String[] getCookie(CookieManager cookieManager, String siteName){
            String cookies = cookieManager.getCookie(siteName);
            String[] cookiesArray=cookies.split(";");
            return cookiesArray;
        }
    
    0 讨论(0)
  • 2020-12-10 13:19

    Oftentimes login requires javascript, try adding this before loadUrl:

    webView.getSettings().setJavaScriptEnabled(true);

    0 讨论(0)
  • 2020-12-10 13:20

    Try to override the shouldOverrideUrlLoading method to make your WebView handle all URL links, and not start a new browser on any link.

    webview.setWebViewClient(new WebViewClient() {  
              @Override  
              public boolean shouldOverrideUrlLoading(WebView view, String url)  
              {  
                return false;  
              }  
    });   
    
    webview.loadUrl(url);
    

    If this doesn't work you can replace your

    cookieManager.setAcceptCookie(true);
    

    to

    cookieManager.setAcceptThirdPartyCookies(true);
    

    because cookieManager.setAcceptCookie(true); doesn't work on Lollipop.

    0 讨论(0)
  • 2020-12-10 13:21

    @Darko.

    CookieManager.getInstance() is the CookieManager instance for your entire application. Hence, you enable or disable cookies for all the webviews in your application.

    Normally it should work if your webview is already initialized: http://developer.android.com/reference/android/webkit/CookieManager.html#getInstance()

    Maybe you call CookieManager.getInstance().setAcceptCookie(true); before you initialize your webview.

    Thanks,

    0 讨论(0)
  • 2020-12-10 13:23

    You have to enable javascript and then getting instance of cookie manager accept cookie By using javascriptenable cookie gets stored

    webView.getSettings().setJavaScriptEnabled(true); CookieManager.getInstance().setAcceptCookie(true);

    0 讨论(0)
提交回复
热议问题