Skip to content

Instantly share code, notes, and snippets.

@justasm
Last active April 21, 2019 10:03
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justasm/8f86eab6108183db93ac to your computer and use it in GitHub Desktop.
Save justasm/8f86eab6108183db93ac to your computer and use it in GitHub Desktop.
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<>();
@Override
public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.addAll(cookies);
}
@Override
public synchronized List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> matchingCookies = new ArrayList<>();
Iterator<Cookie> it = cookieStore.iterator();
while (it.hasNext()) {
Cookie cookie = it.next();
if (cookie.expiresAt() < System.currentTimeMillis()) {
it.remove();
} else if (cookie.matches(url)) {
matchingCookies.add(cookie);
}
}
return matchingCookies;
}
}
@justasm
Copy link
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