Search code examples
androidcookiesandroid-webviewhttpcookie

How to pass cookies fromn Android application to the webpages


I have an Android application which has a login screen. Upon the click of login button I am launching a webview with cookies passed to it. So, I am able to see the contents of the webpage in the webview.

But when I click on the links of the webpage loaded, then the request is faling and from there webpage is not loading. How to pass cookies in such a way that after the login , I can traverse through any number of webpages relentlessly.


Solution

  • Try This..

        WebView webview = new WebView(this);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    
        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(webview.getContext());
        cookieSyncManager.startSync();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();
        cookieManager.setCookie(URL, COOKIE);
        cookieSyncManager.sync();
    
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl(URL);
        setContentView(webview);