Skip to content

Instantly share code, notes, and snippets.

@atoennis
Last active November 10, 2023 01:38
Show Gist options
  • Save atoennis/c12c56a61f0a284cbaa5 to your computer and use it in GitHub Desktop.
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.
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