webviewAndroid技术RxJava、RxAndroid、Retrofit2等系列

OkHttp中自定义CookieJar及Cookie存储机制

2017-08-22  本文已影响109人  GhostInMatrix

Cookie

Cookie最早由网景公司设计并运用到Web通讯中,后被作为规范纳入到RFC2965中。
通常情况下,Cookie会包含如下信息:name expires domain path secure

name:cookie 的名字

expires:过期时间。值是一个日期,一个时刻,而不是一个时长。在OkHttp中,你可以使用该字段在端上建立逻辑,也可以忽略该字段依靠server实现过期的逻辑。

domain:cookie的作用域,指定了cookie将要被发送至哪个域中。默认情况下,domain会被设置为创建该cookie的url所在的域名。但在OkHttp中默认是不存在Cookie机制的,因此这一点需要你来亲自实现完善。像百度这样的网站,会有很多name.baidu.com形式的站点,他们的顶级域名是一致的,但二级域名会有很多,比如waimai.baidu.com,bzclk.baidu.com等。domain的匹配通常是从域名的末尾开始匹配,并将命中的cookie作为有效cookie存储。

path:另一个控制cookie的发送时机的选项。类似于domain,path选项要求请求资源URL中必须存在指定的路径,才会发送cookie。通常是将path的值与请求的URL从开头开始逐个字符串比较完成匹配。如:Set-Cookie:name=Ghost;path=/ghost就要求URL的路径以/ghost开头,如/ghost,/ghostinmatrix都是命中的url。

需要注意的是:cookie匹配验证的顺序首先是domain,然后才会匹配path。

secure:该选项只是一给标记而没有值。只有当一个请求通过SSL或者HTTPS创建的时候,包含secure的cookie才能被发送至服务器。这种cookie内容具有很高价值,如果一纯文本形式传递很有可能被篡改。事实上,机密且敏感的数据是不应该再cookie中存储的,因为cookie整个机制本身就是不安全的。

OkHttp的Cookie支持及调用机制

OkHttp网络库提供了自定义 CookieJar机制来满足应用对Cookie的各种定制需求。在OkHttp的源码中,明确了两点:
1.在不设置自定义CookieJar时,默认为没有Cookie;

public Builder() {
      ...
      cookieJar = CookieJar.NO_COOKIES;
      ...
    }
    

NO_ COOKIES的设置如下,它是一个CookieJar的实现,在需要覆盖的两个方法中直接忽略了任何cookie的处理,即没有cookie。

CookieJar NO_COOKIES = new CookieJar() {
    @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
    }

    @Override public List<Cookie> loadForRequest(HttpUrl url) {
      return Collections.emptyList();
    }  };

2.在设置自定义CookieJar时,


public class CookieJarImpl implements CookieJar {
    private final OkCookieManager cookieManager;

    public CookieJarImpl(OkCookieManager cookieManager) {
        this.cookieManager = cookieManager;
    }

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
         //本地可校验cookie,并根据需要存储
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        //从本地拿取需要的cookie
        return rst;
    }
}

OkHttp在组装请求的过程中,在HttpEngine类中获取了CookieJar中本地的Cookie进行加载:

//HttpEngine.class

public void sendRequest() throws RequestException, RouteException, IOException {
    ...
    Request request = networkRequest(userRequest);
    ...
  }


  
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();
  }

而在获取请求的时候,还是在HttpEngine中,使用saveFromResponse方法将来自server的cookie存储到本地。

/**
   * Flushes the remaining request header and body, parses the HTTP response headers and starts
   * reading the HTTP response body if it exists.
   */
  public void readResponse() throws IOException {
    ...
    receiveHeaders(networkResponse.headers());
    ...
  }
  
 /**
 *从Header中获取Cookie并解析为对象,如果Cookie存在,则saveFromResponse
 */
  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);
  }
  

以上方法都很简单,重点在于Cookie的校验和存储策略。
首先我们需要一个专门负责管理Cookie的类,而这个类显然不能是CookieJar的实现类,于是我们设计一个CookieManager,它要具备一套二级缓存系统,即内存级别和文件级别,如果app关闭,则内存级别会被清空,而用到的cookie都会存到本地文件;app开启则从本地文件加载cookie。

我们如何实现一个CookieManager

知道了Cookie的各项属性和意义之后,就可以根据name、domain、path这三个主要属性进行功能实现了(如果希望功能健全还可以涉及到expired、secure等字段)。首先,我们获取无论是获取还是发送cookie,都会首先以domain为key进行匹配,因此我们的存储容器一定要有一个Map,用来存放不同的domain和对应的 多个Cookie。因此我们这里使用了Map嵌套的方式,一级key为domain、二级key为cookieToken(当然也可以根据自己的情况自由定制)。

public class PersistentCookieStore {


    private static final String COOKIE_PREFS = "Cookies_Prefs";

    //根据各自的业务形态进行定制,可以使用hashMap,甚至也可以选用其他数据结构存储Cookie。例子中使用了HashMap实现,key作为一级域名;value则是以cookieToken为key的Cookie映射,cookieToken的获取见下述方法。
    private final Map<String, ConcurrentHashMap<String, Cookie>> cookies;
    
    
    private final SharedPreferences cookiePrefs;

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

        //将持久化的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);
                    }
                }
            }
        }
    }


    /**
    *cookieToken的获取
    */
    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }
    
    /**
    *cookie的存储
    */
    public void add(Cookie cookie) {
        String name = getCookieToken(cookie);
        if (!cookies.containsKey("XX.com")) {
            cookies.put("XX.com", new ConcurrentHashMap<String, Cookie>());
        }
        cookies.get("XX.com").put(name, cookie);

        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        if (cookies.containsKey("XX.com")) {
            prefsWriter.putString("XX.com", TextUtils.join(",", cookies.get("XX.com").keySet()));
            prefsWriter.putString(name, encodeCookie(new SerializableHttpCookie(cookie)));
            prefsWriter.apply();
        }
    }

    public void add(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);

        if (!cookies.containsKey(url.host())) {
            cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
        }
        cookies.get(url.host()).put(name, cookie);

        //讲cookies持久化到本地
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        if (cookies.containsKey(url.host())) {
            prefsWriter.putString(url.host(), TextUtils.join(",", cookies.get(url.host()).keySet()));
            prefsWriter.putString(name, encodeCookie(new SerializableHttpCookie(cookie)));
            prefsWriter.apply();
        }
    }

    public List<Cookie> get(HttpUrl url) {
        ArrayList<Cookie> ret = new ArrayList<Cookie>();
        if (cookies.containsKey(url.host()))
            ret.addAll(cookies.get(url.host()).values());

        return ret;
    }


    public List<Cookie> get() {
        ArrayList<Cookie> ret = new ArrayList<Cookie>();
        if (cookies.containsKey("XX.com"))
            ret.addAll(cookies.get("XX.com").values());
        return ret;
    }


    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.apply();

        cookies.clear();
        return true;
    }

    public boolean remove() {
        if (cookies.containsKey("XX.com")) {
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();

            for (Cookie cookie : cookies.get("XX.com").values()) {
                String name = getCookieToken(cookie);
                if (cookiePrefs.contains(name)) {
                    prefsWriter.remove(name);
                }
            }
            prefsWriter.remove("XX.com");
            prefsWriter.apply();
            cookies.get("XX.com").clear();
            cookies.remove("XX.com");
            return true;
        } else {
            return false;
        }
    }

    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;
        }
    }


    /**
     * cookies 序列化成 string
     *
     * @param cookie 要序列化的cookie
     * @return 序列化之后的string
     */
    protected String encodeCookie(SerializableHttpCookie 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 = ((SerializableHttpCookie) 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持久化

如果Cookie仅存在于内存中,那么App关闭之后,所有cookie就都消失;而我们期望的是下次打开App的时候依然能够自动登录进入主界面,这就需要我们对Cookie进行文件级别的持久化。但是,okhttp3.Cookie有一个很坑爹的情况:它没有实现Serializable接口,无法序列化。因此,我们只能自己实现序列化:

public class SerializableHttpCookie implements Serializable {

    private transient final Cookie cookie;
    private transient Cookie clientCookies;

    public SerializableHttpCookie(Cookie cookie) {
        this.cookie = cookie;
    }

    public Cookie getCookies() {
        return clientCookies;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(cookie.name());
        out.writeObject(cookie.value());
        out.writeLong(cookie.expiresAt());
        out.writeObject(cookie.domain());
        out.writeObject(cookie.path());
        out.writeBoolean(cookie.secure());
        out.writeBoolean(cookie.httpOnly());
        out.writeBoolean(cookie.hostOnly());
        out.writeBoolean(cookie.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();
    }
}
上一篇下一篇

猜你喜欢

热点阅读