Android cookie manager - How to get all cookies
Asked Answered
V

2

23

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

Virescence answered 17/9, 2016 at 1:7 Comment(2)
Have you find the solution?Yah
maybe this site will help youPhotofluorography
O
3

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 */);
Orose answered 18/7, 2020 at 17:43 Comment(0)
C
0

You can create your own cookie storage and intercept cookies loaded by the WebView. Example using java.net.CookieManager as storage:

val cookieManager = java.net.CookieManager()

webView.webViewClient = object : WebViewClient() {
    override fun onPageFinished(view: WebView?, url: String?) {
        CookieManager.getInstance()
                .getCookie(url)
                ?.let {
                    val uri = URI(url)
                    HttpCookie.parse(it).forEach {
                        cookieManager.cookieStore.add(uri, it)
                    }
                }
    }
}
Caty answered 24/7, 2018 at 11:51 Comment(3)
Is it possible to intercept also third-party cookies with this? Moreover, what is the aim of the API CookieStore.getCookies() if it's not possible to use it? I really do not understand this Android design choice...Titfer
This will only save cookies for explicitly loaded urls, no resources loaded in the background will be handled actually. I'll try to post a better approach soon.Caty
A better approach would be using shouldInterceptRequest() callbacks to intercept all HTTP request and extract cookies while handling the requests yourself. I tried to write a working example, but because WebResourceRequest and WebResourceResponse interfaces are weird and require some tinkering to interoperate with HttpUrlConnection or even OkHttpClient, I failed miserably. Hopefully you'll have more luck with this idea. ;)Caty

© 2022 - 2024 — McMap. All rights reserved.