Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView.loadUrl(url, headers) not working in android

I am setting the cookie in headers and call WebView.loadUrl() with this header but it(Cookie in header) will not work on any android device except 4.4. I have test it on android versions 4.2, 4.3, 4.4, 5.0 and 5.1.

webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);


HashMap <String, String> extraHeaders = new HashMap<String, String>();
extraHeaders.put("Cookie", "{cookie value}");


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

webView.loadUrl(url, extraHeaders);
like image 924
user1041858 Avatar asked Jul 03 '15 09:07

user1041858


3 Answers

Have you tried this

   CookieManager.getInstance().setAcceptCookie(true);
like image 145
Cristiana Chavez Avatar answered Nov 03 '22 14:11

Cristiana Chavez


if you are using Android Lollipop, then

CookieManager.getInstance().setAcceptCookie(true);

won't work. You need to use

CookieManager.getInstance().setAcceptThirdPartyCookies(true);
like image 44
SureshCS50 Avatar answered Nov 03 '22 16:11

SureshCS50


To set cookie use the following method

CookieManager.getInstance().setCookie(BuildConfig.BASE_SERVER_ENDPOINT,COOKIE_VAL);

Make sure the base endpoint matches the base url of the links opened in the webview.

To remove cookie

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                CookieManager.getInstance().removeAllCookies(null);
            } else {
                CookieManager.getInstance().removeAllCookie();
            }
like image 6
rahulrv Avatar answered Nov 03 '22 16:11

rahulrv