Android - extracting cookies after login in webview

徘徊边缘 提交于 2019-11-26 19:43:17

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);
}
vimal1083

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; 
}
Darpan

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.

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!