OkHttp3--CookieJar 持久化Cookie
Okhttp3默认是不持久化Cookie的,想要持久化Cookie就要实现CookieJar接口,并且设置他
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.cookieJar(new PersistenceCookieJar());
简单实现CookieJar接口
public class PersistenceCookieJar implements CookieJar {
List<Cookie> cache = new ArrayList<>();
//Http请求结束,Response中有Cookie时候回调
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//内存中缓存Cookie
cache.addAll(cookies);
}
//Http发送请求前回调,Request中设置Cookie
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
//过期的Cookie
List<Cookie> invalidCookies = new ArrayList<>();
//有效的Cookie
List<Cookie> validCookies = new ArrayList<>();
for (Cookie cookie : cache) {
if (cookie.expiresAt() < System.currentTimeMillis()) {
//判断是否过期
invalidCookies.add(cookie);
} else if (cookie.matches(url)) {
//匹配Cookie对应url
validCookies.add(cookie);
}
}
//缓存中移除过期的Cookie
cache.removeAll(invalidCookies);
//返回List<Cookie>让Request进行设置
return validCookies;
}
};
}
上面代码只是在运行时缓存了Cookie,当App退出的时候Cookie就不存在了。所以我们可以改进一下添加在本地中缓存Cookie的功能
Cookie中数据如何缓存到本地?
我们先来看看Okhttp3的Cookie类
public final class Cookie {
......
private final String name;
private final String value;
private final long expiresAt;
private final String domain;
private final String path;
private final boolean secure;
private final boolean httpOnly;
private final boolean persistent; // True if 'expires' or 'max-age' is present.
private final boolean hostOnly; // True unless 'domain' is present.
......
}
我们仅需缓存这些参数到本地就好了
网友评论