Last active
October 6, 2024 17:37
-
-
Save atoennis/c12c56a61f0a284cbaa5 to your computer and use it in GitHub Desktop.
WebViews automatically persist cookies into a android.webkit.CookieManager. Need to store cookies from a WebView into a java.net.CookieManager? Here's one way to do so.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
webView.setWebViewClient(new WebViewClient() { | |
@Override | |
public boolean shouldOverrideUrlLoading(WebView view, String url) { | |
String cookieStr = CookieManager.getInstance().getCookie(url); // android.webkit.CookieManager | |
storeCookies(url, cookieStr); | |
return super.shouldOverrideUrlLoading(view, url); | |
} | |
// Convert cookie string into a list of cookies. Persist cookies in a java.net.CookieStore | |
private void storeCookies(String url, String cookieStr) { | |
if (cookieStr != null && !cookieStr.isEmpty()) { | |
URI uri = new URI(url); | |
List<HttpCookie> cookies = HttpCookie.parse(cookieStr); | |
for (HttpCookie cookie : cookies) { | |
cookieStore.add(uri, cookie); // java.net.CookieStore from a java.net.CookieManager | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment