Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
OkHttp 3 non-persistent CookieJar with an ACCEPT_ALL policy
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
public class NonPersistentCookieJar implements CookieJar {
private final Set<Cookie> cookieStore = new LinkedHashSet<>();
public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
public synchronized List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> matchingCookies = new ArrayList<>();
Iterator<Cookie> it = cookieStore.iterator();
while (it.hasNext()) {
Cookie cookie =;
if (cookie.expiresAt() < System.currentTimeMillis()) {
} else if (cookie.matches(url)) {
return matchingCookies;

This comment has been minimized.

Copy link

joeymetal commented Apr 19, 2016

Hello thank you was looking for a solution about
2 days and very difficult
but now I found


This comment has been minimized.

Copy link

haridaniel commented Feb 14, 2017

Smart, but I found a bug: if it stores same cookie with different values, the old ones won't be overwritten but loaded as duplicates on request.


This comment has been minimized.

Copy link
Owner Author

justasm commented Aug 12, 2017

@haridaniel you're right, cookies should override matching older cookies according to the specs in RFC 6265 5.3 Storage Model.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.