Android 开发中 Cookie 持久化研究

参考:
android WebView的cookie机制
Android中Cookie获取、保存以及同步
OkHttp3实现Cookies持续化管理

1.先看一下Chrome中的Cookie信息

访问首页信息时:

Android 开发中 Cookie 持久化研究_第1张图片
1.第一次调用的Header信息
Android 开发中 Cookie 持久化研究_第2张图片
2.再次请求时Header信息

第一次请求时,服务器会在Response Header中带过来一个Set-Cookie,内容为JSESSIONID=C3E668A891BA4E1C160C91A7EBEAA540.h2;再次请求时,浏览器会在Requst Header中的Cookie将JSESSIONID带上。
在浏览器中调用登录接口时:

Android 开发中 Cookie 持久化研究_第3张图片
3.直接调用登录接口
Android 开发中 Cookie 持久化研究_第4张图片
4.打开首页后再调用登录接口

2.WebView的cookie机制

WebView是基于webkit内核的UI控件,相当于一个浏览器客户端。它会在本地维护每次会话的cookie(保存在data/data/package_name/app_WebView/Cookies.db)。如图:
Android 开发中 Cookie 持久化研究_第5张图片

查看APP cookie

当WebView加载URL的时候,WebView会从本地读取该URL对应的cookie,并携带该cookie与服务器进行通信。WebView通过android.webkit.CookieManager类来维护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 会被新的给替换掉,注意是host、path和name都相同的。url参数是你要为哪个cookie设置,而value和服务器返回设置sookie的方法'Set-Cookie‘是一致的。也就是一个url的多个cookie,要调用多次setCookie,而每一次调用value的值都类似于:
cookie + ";Max-Age=3600" + ";Domain=.163.com" + ";Path = /" // 当然还可以加上版本等信息

一般写法:

//value参数不要忘记加domain和path
cookieManager.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue() + 
"; domain=" + cookie.getDomain() + "; path=" + cookie.getPath());

注意这里为什么第一个参数写了个cookie.getDomain(),而不是像api里边说的url这涉及到了cookie的知识,设置cookie时,会先检测cookie的Domain是否和url网址的域名一致,如果不一致设置cookie失败。所以url在里边起到作用,就是检测Domain域名。
注意,只有cookie的domain和path与请求的URL匹配才会发送这个cookie,所以设置cookie的时候value参数不要忘记加domain和path,如上面代码。

如何做:

下面我们就通过CookieManager将cookie同步到WebView中。之前同步cookie需要用到CookieSyncManager类,现在这个类已经被deprecated。如今WebView已经可以在需要的时候自动同步cookie了,所以不再需要创建CookieSyncManager类的对象来进行强制性的同步cookie了。现在只需要获得 CookieManager的对象将cookie设置进去就可以了。

  • 第一步:登录时从服务器的返回头中取出cookie根据Http请求的客户端不同,取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;
}

如果设置成功,通过cookieManager.getCookie(url)方法就可取得刚才设置的cookie,下面我们查看一下Cookie数据库中发生的变化。如图:


Android 开发中 Cookie 持久化研究_第6张图片
查看WebView cookie

3. OkHttp 中实现 Cookie 持久化管理

在OkHttp3中,对cookie而言,新增了两个类 Cookiejar 、 Cookie 两个类,在了解这两个类之前,先去看一下 HttpEngine 关于cookie管理的变化

private Request networkRequest(Request request) throws IOException {
Request.Builder result = request.newBuilder();

    ....

List cookies = client.cookieJar().loadForRequest(request.url());
if (!cookies.isEmpty()) {
  result.header("Cookie", cookieHeader(cookies));
}

   ....

return result.build();
}

private String cookieHeader(List 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 cookies = Cookie.parseAll(userRequest.url(), headers);
if (cookies.isEmpty()) return;

client.cookieJar().saveFromResponse(userRequest.url(), cookies);
}

通过以上几个关键方法,可以很明显的感觉到作者的意图了,为了更加自由定制化的cookie管理。其中 loadForRequest() 、 saveFromResponse() 这两个方法最为关键,分别是在发送时向request header中加入cookie,在接收时,读取response header中的
Cookies持久化对Cookies持久化的方案,与之前版本并无很大区别,还是参考 android-async-http 这个库,主要参考其中两个类:

  • PersistentCookieStore
  • SerializableHttpCookie
    与之前版本的区别是要将对 java.net.HttpCookie 这个类的缓存处理换成对 okhttp3.Cookie 的处理,其他方面几乎一样。

SerializableOkHttpCookies
主要做两件事:将Cookie对象输出为ObjectStream
将ObjectStream序列化成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();
    }
}

PersistentCookieStore
根据一定的规则去缓存或者获取Cookie
SharedPreferences 存储

public class PersistentCookieStore {

    private static final String LOG_TAG = "PersistentCookieStore";
    private static final String COOKIE_PREFS = "Cookies_Prefs";
    private final Map> cookies;
    private final SharedPreferences cookiePrefs;

    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new HashMap<>();

        //将持久化的cookies缓存到内存中 即map cookies
        Map prefsMap = cookiePrefs.getAll();
        for (Map.Entry 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());
                        }
                        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缓存到内存中 如果缓存过期 就重置此cookie
        if (!cookie.persistent()) {
            if (!cookies.containsKey(url.host())) {
                cookies.put(url.host(), new ConcurrentHashMap());
            }
            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 get(HttpUrl url) {
        ArrayList 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 getCookies() {
        ArrayList 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;
    }

    /**
     * 二进制数组转十六进制字符串
     *
     * @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;
    }
}

最终效果
完成对Cookie持久化之后,就可以对Cookiejar进行进一步修改了,最终效果:
/* 自动管理Cookies */

private class CookiesManager implements CookieJar {

    private final PersistentCookieStore cookieStore = new PersistentCookieStore(getApplicationContext());

    @Override
    public void saveFromResponse(HttpUrl url, List cookies) {
        if (cookies != null && cookies.size() > 0) {
            for (Cookie item : cookies) {
                cookieStore.add(url, item);
            }
        }
    }

    @Override
    public List loadForRequest(HttpUrl url) {
        List cookies = cookieStore.get(url);
        return cookies;
    }
}

最后设置OkHttpClient
//持久化管理

  OkHttpClient.Builder builder = new OkHttpClient.Builder();
  Cookiebuilder.cookieJar(new CookiesManager());

你可能感兴趣的:(Android 开发中 Cookie 持久化研究)