Android - extracting cookies after login in webview

83,524

Solution 1

You can extract all cookies current url by this way from webview as string:

@Override
public void onPageFinished(WebView view, String url){
    String cookies = CookieManager.getInstance().getCookie(url);
    Log.d(TAG, "All the cookies in a string:" + cookies);
}

Solution 2

It was a quite late , but it might help someone

you can get the cookie value using this

getCookie("http://www.example.com","cookieName");

Declare the function as

public String getCookie(String siteName,String cookieName){     
    String CookieValue = null;

    CookieManager cookieManager = CookieManager.getInstance();
    String cookies = cookieManager.getCookie(siteName);       
    String[] temp=cookies.split(";");
    for (String ar1 : temp ){
        if(ar1.contains(cookieName)){
            String[] temp1=ar1.split("=");
            CookieValue = temp1[1];
            break;
        }
    }              
    return CookieValue; 
}

Solution 3

This answer is derived from @vimal1083. It returns the values in a Map, and of course written in Kotlin.

fun getCookieMap(siteName: String): Map<String,String> {

    val manager = CookieManager.getInstance()
    val map = mutableMapOf<String,String>()

    manager.getCookie(siteName)?.let {cookies ->
        val typedArray = cookies.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        for (element in typedArray) {
            val split = element.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()

            if(split.size >= 2) {
                map[split[0]] = split[1]
            } else if(split.size == 1) {
                map[split[0]] = ""
            }
        }
    }

    return map
}

Solution 4

Check this link - Pass cookies from HttpURLConnection (java.net.CookieManager) to WebView (android.webkit.CookieManager)

If you want to get cookies from webview, you will have to use android.webkit.CookieManager, from any HttpUrlConnection, however, you can extract cookies useing java.net.CookieStore

You will need to parse the string where you are getting all the cookies.

Share:
83,524
elgoog
Author by

elgoog

Updated on December 24, 2021

Comments

  • elgoog
    elgoog over 2 years

    I have an application that opens a url in a webview, the user must then login to a site through the webview and receives a cookie once logged in. I'm having problems getting cookies after login.

    The problem is, I can achieve this using android.webkit.CookieManager, and output all cookies in a single string.

    However, I want to achieve it using the a cookie store (as in java.net.CookieStore) so I need to be using java.net.CookieManager.

    I'm using the following code within the onPageFinished() of a WebViewClient. I know the issue is with opening a new connection, where I need to be getting the content from the current page. I'd appreciate some help, thanks

            @Override
            public void onPageFinished(WebView view, String url){
    
                Log.d(TAG, "Finished loading: " + url);
    
                CookieSyncManager syncManager = CookieSyncManager.createInstance(Main.this);
                syncManager.sync();
    
                CookieManager manager = new CookieManager();
                manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
                CookieHandler.setDefault(manager);
    
                try {
                    URL blah = new URL(url);
                    HttpURLConnection con = (HttpURLConnection) blah.openConnection();
                    readStream(con.getInputStream()); // outputting html
                } 
                catch (Exception e) {
                }
    
                CookieStore cookieJar = manager.getCookieStore();
                List<HttpCookie> cookies = cookieJar.getCookies();
    
                for (HttpCookie cookie: cookies) {
                    Log.d(TAG, "cookie name : "+cookie.getName().toString());
                }
            }
    
  • Admin
    Admin over 10 years
    mrboyfox, do you have any idea about this : stackoverflow.com/questions/19256509/…
  • Radu Simionescu
    Radu Simionescu over 9 years
    why do you need the [] in those regexes which are used for splitting strings?
  • gengkev
    gengkev over 9 years
    @RaduSimionescu they don't seem necessary to me, but they won't hurt, either
  • Radu Simionescu
    Radu Simionescu over 9 years
    @gengkev in that case, why not type in something like "(([;])){1}{1,1}" ?
  • gengkev
    gengkev over 9 years
    @RaduSimionescu :) well, i suppose the author might have taken the regex from another piece of code and modified it?
  • vimal1083
    vimal1083 over 9 years
    Sorry guys i removed it , Thanks for your comments
  • althaus
    althaus almost 9 years
    Be aware that using contains will find false entries, when a cookie value contains the name to look for: FOO=BAR; BAR=FOO
  • davehenry
    davehenry over 8 years
    This will break if your cookie value contains the = character
  • Vitalij Kornijenko
    Vitalij Kornijenko almost 8 years
    @davehenry To avoid that, add a second argument to split method, like this: String[] temp1=ar1.split("=",2);
  • Kaizie
    Kaizie over 7 years
    As @althaus says, "if(ar1.contains(CookieName)){" this is dangerous, it may be better "if(ar1.indexOf(CookieName) == 0){" then you make sure you are looking for the name of the cookie and not some intermediate string that may cause a false positive.
  • vimal1083
    vimal1083 over 7 years
    Thanks @AlpAltunel
  • Itay Bianco
    Itay Bianco over 5 years
    doesn't work when the page has a redirect through JS. onPageFinished is not called for every page.
  • SBotirov
    SBotirov over 5 years
    @ItayBianco You can add another answer to your a situation if you have a solution too. It is will be great to developers which is looking solution to this a situation.
  • Kalyaganov Alexey
    Kalyaganov Alexey almost 5 years
    Does not work if cookie has SameSite flag. CookieManager just does not return that kind of cookie
  • MartianMartian
    MartianMartian about 2 years
    import android.webkit.CookieManager;
  • MartianMartian
    MartianMartian about 2 years
    import android.webkit.CookieManager;