Skip to content

Instantly share code, notes, and snippets.

@swissonid
Last active November 15, 2017 10:19
Show Gist options
  • Save swissonid/c328dbf93c846640275d1bfa7073deb9 to your computer and use it in GitHub Desktop.
Save swissonid/c328dbf93c846640275d1bfa7073deb9 to your computer and use it in GitHub Desktop.
Sync Webview Cookie store with OkHttpClient
import android.support.annotation.NonNull;
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;
public class WebViewCookieJar implements CookieJar {
private final CookieManager cookieManager;
public WebViewCookieJar(CookieManager webkitCookieManger) {
this.cookieManager = webkitCookieManger;
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
String urlString = url.toString();
for (Cookie cookie : cookies) {
cookieManager.setCookie(urlString, cookie.toString());
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
String urlString = url.toString();
String cookiesString = cookieManager.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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment