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()); } }
Cookie From API Service to WebViewThe WKWebsiteDataStore store cookies that can be accessed by all WKWebview .
Open your browser. Android browser: Go to Menu > More > Settings or Menu > Settings > Privacy & Security. Chrome: Go to Menu > Settings > Privacy. Android browser: Tap Clear cache, Clear history, and Clear all cookie data as appropriate.
The WebView class is an extension of Android's View class that allows you to display web pages as a part of your activity layout. It does not include any features of a fully developed web browser, such as navigation controls or an address bar. All that WebView does, by default, is show a web page.
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); }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With