OkHttp3 的 Cookie 持久化其实网上的文章很多。我写这篇文章只是为了下次再做Cookie持久化的时候可以拿来就用。
CookieJar 就是OkHttp3 提供用来获取Cookie的接口:很简单 该接口有2个方法,主要用来存Cookie和获取Cooki。
public class MyCookiesJar implements CookieJar {
private static final String TAG = "CookiesManager";
// 持久化的存储 Cookie的类
private final PersistentCookieStore mCookieStore = PersistentCookieStore.getInstance(Engine.getInstance().getContext());
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
if (cookies != null && cookies.size() > 0) {
String host = url.host();
if (Build.VERSION.SDK_INT < 21) {
CookieSyncManager.createInstance(Engine.getInstance().getContext());
}
for (Cookie item : cookies) {
Logger.d(TAG, "url = " + url + ", name: " + item.name() + "=" + item.value());
mCookieStore.add(url, item);
// 给 Webview 中传入Cookie
CookieManager.getInstance().setAcceptCookie(true);
//TODO ...ZJT 替换下面的代码
CookieManager.getInstance().setCookie(item.domain(), item.name() + "=" + item.value() + "; domain=" + item.domain() + "; path=" + item.path());
// CookieManager.getInstance().setCookie(host, item.value());
}
Logger.d(TAG, "url = " + url + ", cookie: " + CookieManager.getInstance().getCookie(host));
if (Build.VERSION.SDK_INT < 21) {
CookieSyncManager.getInstance().sync();
} else {
CookieManager.getInstance().flush();
}
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
return mCookieStore.get(url);
}
}
其中的 PersistentCookieStore 是用来持久化存储 Cookie 的类。
代码如下:
public class PersistentCookieStore {
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "Cookies_Prefs";
private final Map<String, Map<String, Cookie>> cookies;
private final SharedPreferences cookiePrefs;
private static PersistentCookieStore mInstance;
public static PersistentCookieStore getInstance(Context context) {
if (mInstance == null) {
mInstance = new PersistentCookieStore(context.getApplicationContext());
}
return mInstance;
}
private PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<>();
//将持久化的cookies缓存到内存中 即map cookies
Map<String, ?> prefsMap = cookiePrefs.getAll();
for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
if (!cookies.containsKey(entry.getKey())) {
cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(entry.getKey()).put(name, decodedCookie);
}
}
}
}
}
@Nullable
protected String getCookieToken(Cookie cookie) {
if (cookie == null) return null;
return cookie.name() + "@" + cookie.domain();
}
public void add(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
if(name == null) {
return;
}
//将cookies缓存到内存中 如果缓存过期 就重置此cookie
if (!cookie.persistent() || cookie.expiresAt() > System.currentTimeMillis()) {
if (!cookies.containsKey(url.host())) {
cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
}
cookies.get(url.host()).put(name, cookie);
} else {
if (cookies.containsKey(url.host())) {
cookies.get(url.host()).remove(name);
}
}
//讲cookies持久化到本地
if (cookies.get(url.host()) != null) {
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
prefsWriter.apply();
}
}
public List<Cookie> get(HttpUrl url) {
ArrayList<Cookie> ret = new ArrayList<>();
if (cookies.containsKey(url.host()))
ret.addAll(cookies.get(url.host()).values());
return ret;
}
public boolean removeAll() {
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.apply();
cookies.clear();
CookieSyncManager.createInstance(Engine.getInstance().getContext());
CookieManager.getInstance().removeAllCookie();
CookieSyncManager.getInstance().sync();
return true;
}
public boolean remove(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
if(name == null) {
return false;
}
if (cookies.containsKey(url.host()) && cookies.get(url.host()).containsKey(name)) {
cookies.get(url.host()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if (cookiePrefs.contains(name)) {
prefsWriter.remove(name);
}
prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
prefsWriter.apply();
return true;
} else {
return false;
}
}
public List<Cookie> getCookies() {
ArrayList<Cookie> ret = new ArrayList<>();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
}
/**
* cookies 序列化成 string
*
* @param cookie 要序列化的cookie
* @return 序列化之后的string
*/
protected String encodeCookie(SerializableOkHttpCookies cookie) {
if (cookie == null)
return null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (IOException e) {
Logger.e(LOG_TAG, "IOException in encodeCookie", e);
return null;
}
return byteArrayToHexString(os.toByteArray());
}
/**
* 将字符串反序列化成cookies
*
* @param cookieString cookies string
* @return cookie object
*/
protected Cookie decodeCookie(String cookieString) {
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
} catch (IOException e) {
Logger.e(LOG_TAG, "IOException in decodeCookie", e);
} catch (ClassNotFoundException e) {
Logger.e(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
/**
* 二进制数组转十六进制字符串
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes) {
int v = element & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase(Locale.US);
}
/**
* 十六进制字符串转二进制数组
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
}
return data;
}
}
其中的 SerializableOkHttpCookies
是序列化Cookie一般本地存储,如下:
public class SerializableOkHttpCookies implements Serializable {
private transient final Cookie cookies;
private transient Cookie clientCookies;
public SerializableOkHttpCookies(Cookie cookies) {
this.cookies = cookies;
}
public Cookie getCookies() {
Cookie bestCookies = cookies;
if (clientCookies != null) {
bestCookies = clientCookies;
}
return bestCookies;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookies.name());
out.writeObject(cookies.value());
out.writeLong(cookies.expiresAt());
out.writeObject(cookies.domain());
out.writeObject(cookies.path());
out.writeBoolean(cookies.secure());
out.writeBoolean(cookies.httpOnly());
out.writeBoolean(cookies.hostOnly());
out.writeBoolean(cookies.persistent());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
long expiresAt = in.readLong();
String domain = (String) in.readObject();
String path = (String) in.readObject();
boolean secure = in.readBoolean();
boolean httpOnly = in.readBoolean();
boolean hostOnly = in.readBoolean();
boolean persistent = in.readBoolean();
Cookie.Builder builder = new Cookie.Builder();
builder = builder.name(name);
builder = builder.value(value);
builder = builder.expiresAt(expiresAt);
builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain);
builder = builder.path(path);
builder = secure ? builder.secure() : builder;
builder = httpOnly ? builder.httpOnly() : builder;
clientCookies =builder.build();
}
}
然后再加上一个 CookieInteceptor
用来接口请求的时候带上 Cookie,如下:
public class CookieInterceptor implements Interceptor {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
String cookies = "";
for (Cookie cookie : PersistentCookieStore.getInstance(Engine.getInstance().getContext()).getCookies()) {
if (!cookies.contains(cookie.name())) {
cookies = cookies + cookie.name() + "=" + cookie.value() + ";";
}
}
Log.e("CookiesManager", "cookies = "+cookies);
Request request = chain.request().newBuilder()
.addHeader("Cookie", cookies)
.build();
return chain.proceed(request);
}
}
最后的用法如下:
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.eventListenerFactory(HttpEventListener.FACTORY)
.connectTimeout(20*1000, TimeUnit.MILLISECONDS)
.readTimeout(20*1000, TimeUnit.MILLISECONDS)
.writeTimeout(20*1000, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true);
if (HeaderManager.getInstance().getHeaders() != null && !HeaderManager.getInstance().getHeaders().isEmpty()) {
builder.addInterceptor(new HeaderInterceptor(HeaderManager.getInstance().getHeaders()));
}
builder
.addInterceptor(new CookieInterceptor()) // 接口请求添加cookie
.addInterceptor(new ChangeBaseUrlInterceptor())
.addInterceptor(new HttpLoggingInterceptor(msg -> Logger.dOrigin("API", msg)).setLevel(HttpLoggingInterceptor.Level.BODY))
.cookieJar(new MyCookiesJar()); // cookiejar
return builder.build();
最后在登出App的时候 调用 PersistentCookieStore.getInstance(mContext).removeAll();
来清除Cookie