Android cookie manager - How to get all cookies

darewreck picture darewreck · Sep 17, 2016 · Viewed 14.5k times · Source

I need to get all the cookies that are stored in the webview. Currently the default webview.

https://developer.android.com/reference/android/webkit/CookieManager.html

Currently it only supports:

  • getCookie(String url)

I need the ability to get all the cookies without knowing the exact domain name.

Any Advice Appreciated Thanks, D

Answer

mohamed morsi picture mohamed morsi · Jul 18, 2020

In Java, as I understood you are using webView and you want to get all cookies of specific previewed URL, you can get current URL from webView client an pass it as a parameter to getCookie()

String cookies = CookieManager.getInstance().getCookie(webView.getUrl());

as a best practice, you should try it after page loaded like this

    WebView webView = findViewById(R.id.webview_id);
    WebViewClient webViewClient = new WebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String cookies = CookieManager.getInstance().getCookie(view.getUrl());
            // save cookies or call new fun to handle actions 
            //  newCookies(cookies);
        }
    };
    webView.setWebViewClient(webViewClient);
    //webView.loadUrl(/*what ever url you want to load */);