Skip to content

Instantly share code, notes, and snippets.

@hungps
Last active January 6, 2024 11:39
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hungps/8cb6d8484bb20e47d241cc8e117fa705 to your computer and use it in GitHub Desktop.
Save hungps/8cb6d8484bb20e47d241cc8e117fa705 to your computer and use it in GitHub Desktop.
Cookie jar that handles syncing okhttp cookies with Webview cookie manager
import android.webkit.CookieManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
/**
* Provides a synchronization point between the webview cookie store and okhttp3.OkHttpClient cookie store
*/
public final class WebviewCookieHandler implements CookieJar {
private CookieManager webviewCookieManager = CookieManager.getInstance();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
String urlString = url.toString();
for (Cookie cookie : cookies) {
webviewCookieManager.setCookie(urlString, cookie.toString());
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
String urlString = url.toString();
String cookiesString = webviewCookieManager.getCookie(urlString);
if (cookiesString != null && !cookiesString.isEmpty()) {
//We can split on the ';' char as the cookie manager only returns cookies
//that match the url and haven't expired, so the cookie attributes aren't included
String[] cookieHeaders = cookiesString.split(";");
List<Cookie> cookies = new ArrayList<>(cookieHeaders.length);
for (String header : cookieHeaders) {
cookies.add(Cookie.parse(url, header));
}
return cookies;
}
return Collections.emptyList();
}
}
@hungps
Copy link
Author

hungps commented Apr 7, 2017

Usage:

//import okhttp3.OkHttpClient;

OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new WebviewCookieHandler())
                .build();

@Radiokot
Copy link

Radiokot commented Jan 6, 2024

Nice one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment