參考:
android WebView的cookie機(jī)制
Android中Cookie獲取器腋、保存以及同步
OkHttp3實(shí)現(xiàn)Cookies持續(xù)化管理
1.先看一下Chrome中的Cookie信息
訪問首頁信息時(shí):
第一次請(qǐng)求時(shí),服務(wù)器會(huì)在Response Header中帶過來一個(gè)Set-Cookie,內(nèi)容為JSESSIONID=C3E668A891BA4E1C160C91A7EBEAA540.h2;再次請(qǐng)求時(shí),瀏覽器會(huì)在Requst Header中的Cookie將JSESSIONID帶上。
在瀏覽器中調(diào)用登錄接口時(shí):
2.WebView的cookie機(jī)制
WebView是基于webkit內(nèi)核的UI控件搜骡,相當(dāng)于一個(gè)瀏覽器客戶端。它會(huì)在本地維護(hù)每次會(huì)話的cookie(保存在data/data/package_name/app_WebView/Cookies.db)。如圖:查看APP cookie
當(dāng)WebView加載URL的時(shí)候,WebView會(huì)從本地讀取該URL對(duì)應(yīng)的cookie辩尊,并攜帶該cookie與服務(wù)器進(jìn)行通信。WebView通過android.webkit.CookieManager類來維護(hù)cookie趴乡。CookieManager是WebView的cookie管理類对省。
CookieManager.setCookie()方法:
/**
* Sets a cookie for the given URL. Any existing cookie with the same host,
* path and name will be replaced with the new cookie. The cookie being set
* must not have expired and must not be a session cookie, otherwise it
* will be ignored.
*
* @param url the URL for which the cookie is set
* @param value the cookie as a string, using the format of the 'Set-Cookie'
* HTTP response header
*/
public void setCookie(String url, String value) {
throw new MustOverrideException();
}
注:host、path和name相同的cookie 會(huì)被新的給替換掉晾捏,注意是host蒿涎、path和name都相同的。url參數(shù)是你要為哪個(gè)cookie設(shè)置惦辛,而value和服務(wù)器返回設(shè)置sookie的方法'Set-Cookie‘是一致的劳秋。也就是一個(gè)url的多個(gè)cookie,要調(diào)用多次setCookie胖齐,而每一次調(diào)用value的值都類似于:
cookie + ";Max-Age=3600" + ";Domain=.163.com" + ";Path = /" // 當(dāng)然還可以加上版本等信息
一般寫法:
//value參數(shù)不要忘記加domain和path
cookieManager.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue() +
"; domain=" + cookie.getDomain() + "; path=" + cookie.getPath());
注意這里為什么第一個(gè)參數(shù)寫了個(gè)cookie.getDomain()玻淑,而不是像api里邊說的url這涉及到了cookie的知識(shí),設(shè)置cookie時(shí)呀伙,會(huì)先檢測(cè)cookie的Domain是否和url網(wǎng)址的域名一致补履,如果不一致設(shè)置cookie失敗。所以u(píng)rl在里邊起到作用剿另,就是檢測(cè)Domain域名箫锤。
注意贬蛙,只有cookie的domain和path與請(qǐng)求的URL匹配才會(huì)發(fā)送這個(gè)cookie,所以設(shè)置cookie的時(shí)候value參數(shù)不要忘記加domain和path谚攒,如上面代碼阳准。
如何做:
下面我們就通過CookieManager將cookie同步到WebView中。之前同步cookie需要用到CookieSyncManager類馏臭,現(xiàn)在這個(gè)類已經(jīng)被deprecated野蝇。如今WebView已經(jīng)可以在需要的時(shí)候自動(dòng)同步cookie了,所以不再需要?jiǎng)?chuàng)建CookieSyncManager類的對(duì)象來進(jìn)行強(qiáng)制性的同步cookie了括儒。現(xiàn)在只需要獲得 CookieManager的對(duì)象將cookie設(shè)置進(jìn)去就可以了绕沈。
第一步:登錄時(shí)從服務(wù)器的返回頭中取出cookie根據(jù)Http請(qǐng)求的客戶端不同,取cookie的方式也不同塑崖,以HttpURLcollection為例:
String cookieStr = conn.getHeaderField("Set-Cookie");
第二步:將cookie同步到WebView中
/**
* 將cookie同步到WebView
* @param url WebView要加載的url
* @param cookie 要同步的cookie
* @return true 同步cookie成功七冲,false同步cookie失敗
* @Author JPH
*/
public static boolean syncCookie(String url,String cookie) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.createInstance(context);
}
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie(url, cookie);//如果沒有特殊需求,這里只需要將session id以"key=value"形式作為cookie即可
String newCookie = cookieManager.getCookie(url);
return TextUtils.isEmpty(newCookie)?false:true;
}
如果設(shè)置成功规婆,通過cookieManager.getCookie(url)方法就可取得剛才設(shè)置的cookie澜躺,下面我們查看一下Cookie數(shù)據(jù)庫(kù)中發(fā)生的變化。如圖:
3. OkHttp 中實(shí)現(xiàn) Cookie 持久化管理
在OkHttp3中抒蚜,對(duì)cookie而言掘鄙,新增了兩個(gè)類 Cookiejar 、 Cookie 兩個(gè)類嗡髓,在了解這兩個(gè)類之前操漠,先去看一下 HttpEngine 關(guān)于cookie管理的變化
private Request networkRequest(Request request) throws IOException {
Request.Builder result = request.newBuilder();
....
List<Cookie> cookies = client.cookieJar().loadForRequest(request.url());
if (!cookies.isEmpty()) {
result.header("Cookie", cookieHeader(cookies));
}
....
return result.build();
}
private String cookieHeader(List<Cookie> cookies) {
StringBuilder cookieHeader = new StringBuilder();
for (int i = 0, size = cookies.size(); i < size; i++) {
if (i > 0) {
cookieHeader.append("; ");
}
Cookie cookie = cookies.get(i);
cookieHeader.append(cookie.name()).append('=').append(cookie.value());
}
return cookieHeader.toString();
}
public void receiveHeaders(Headers headers) throws IOException {
if (client.cookieJar() == CookieJar.NO_COOKIES) return;
List<Cookie> cookies = Cookie.parseAll(userRequest.url(), headers);
if (cookies.isEmpty()) return;
client.cookieJar().saveFromResponse(userRequest.url(), cookies);
}
通過以上幾個(gè)關(guān)鍵方法,可以很明顯的感覺到作者的意圖了饿这,為了更加自由定制化的cookie管理浊伙。其中 loadForRequest() 、 saveFromResponse() 這兩個(gè)方法最為關(guān)鍵长捧,分別是在發(fā)送時(shí)向request header中加入cookie嚣鄙,在接收時(shí),讀取response header中的
Cookies持久化對(duì)Cookies持久化的方案串结,與之前版本并無很大區(qū)別哑子,還是參考 android-async-http 這個(gè)庫(kù),主要參考其中兩個(gè)類:
- PersistentCookieStore
- SerializableHttpCookie
與之前版本的區(qū)別是要將對(duì) java.net.HttpCookie 這個(gè)類的緩存處理換成對(duì) okhttp3.Cookie 的處理肌割,其他方面幾乎一樣卧蜓。
SerializableOkHttpCookies
主要做兩件事:將Cookie對(duì)象輸出為ObjectStream
將ObjectStream序列化成Cookie對(duì)象
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();
}
}
PersistentCookieStore
根據(jù)一定的規(guī)則去緩存或者獲取Cookie
SharedPreferences 存儲(chǔ)
public class PersistentCookieStore {
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "Cookies_Prefs";
private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;
private final SharedPreferences cookiePrefs;
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<>();
//將持久化的cookies緩存到內(nèi)存中 即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);
}
}
}
}
}
protected String getCookieToken(Cookie cookie) {
return cookie.name() + "@" + cookie.domain();
}
public void add(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
//將cookies緩存到內(nèi)存中 如果緩存過期 就重置此cookie
if (!cookie.persistent()) {
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持久化到本地
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();
return true;
}
public boolean remove(HttpUrl url, Cookie cookie) {
String name = getCookieToken(cookie);
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) {
Log.d(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) {
Log.d(LOG_TAG, "IOException in decodeCookie", e);
} catch (ClassNotFoundException e) {
Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
}
return cookie;
}
/**
* 二進(jìn)制數(shù)組轉(zhuǎn)十六進(jìn)制字符串
*
* @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);
}
/**
* 十六進(jìn)制字符串轉(zhuǎn)二進(jìn)制數(shù)組
*
* @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;
}
}
最終效果
完成對(duì)Cookie持久化之后,就可以對(duì)Cookiejar進(jìn)行進(jìn)一步修改了把敞,最終效果:
/* 自動(dòng)管理Cookies */
private class CookiesManager implements CookieJar {
private final PersistentCookieStore cookieStore = new PersistentCookieStore(getApplicationContext());
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
if (cookies != null && cookies.size() > 0) {
for (Cookie item : cookies) {
cookieStore.add(url, item);
}
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url);
return cookies;
}
}
最后設(shè)置OkHttpClient
//持久化管理
OkHttpClient.Builder builder = new OkHttpClient.Builder();
Cookiebuilder.cookieJar(new CookiesManager());