Retrofit OKHttp 教你怎么持久化管理Cookie

投稿作者:黄海杰 原文链接: http://blog.csdn.net/lyhhj/article/details/51345386

绪论

最近小编有点忙啊,项目比较紧,所以一直在忙活项目,继之前的自定义组件之后就没再写博客了,如果你没看到之前的自定义组件你可以看一下: Android自定义下拉刷新动画—仿百度外卖下拉刷新 Android自定义组合控件—-教你如何自定义下拉刷新和左滑删除 效果还行,源码也已经传到我的Github上了。 那么今天小编来给大家分享点什么呢?对,就是它:Retrofit,话说Retrofit最近真的很火啊,Retrofit+OKHttp现在似乎已经成为了Android网络请求框架的主流框架了吧,小编之前用的是XUtils框架,个人感觉也不错,也更新到了Xutils3,但是毕竟Retrofit是Square出的,所以小编还是忍不住需要探索一下。 鉴于现在Retrofit现在网上很多教程,所以基本的使用方法就不介绍了,小编也不重复造轮子了,如果你还不会用,看看下面几篇文章: Retrofit 2.0使用详解,配合OkHttp、Gson,Android最强网络请求框架 Retrofit 2.0:有史以来最大的改进 Retrofit初探和简单使用

持久化Cookie

今天小编要讲的是,怎么持久化管理你的Cookie,也就是实现用户免登陆过程。 首先说一下需求,后台大哥哥是这样告诉我的:我们的用户登录需要你在本地管理cookie,用户下次进来的时候不需要再登录,调用其他接口的时候将用户的cookie和session放到请求头里面。我果断的答应了,因为之前用Xutils的时候也这么做过,当我去网上找资料的时候发现并没有很好的资料。因为Retrofit内部是Ok来实现的,所以方向可以找到Ok管理Cookie,好了,方向找到了,我们来看一下OKHttp: OKHttp3.0之前和之后有很大的改动: 3.0之前:

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

  //例行省略....

  CookieHandler cookieHandler = client.getCookieHandler();
  if (cookieHandler != null) {
    // Capture the request headers added so far so that they can be offered to the CookieHandler.
    // This is mostly to stay close to the RI; it is unlikely any of the headers above would
    // affect cookie choice besides "Host".
    Map<String, List<String>> headers = OkHeaders.toMultimap(result.build().headers(), null);

    Map<String, List<String>> cookies = cookieHandler.get(request.uri(), headers);

    // Add any new cookies to the request.
    OkHeaders.addCookies(result, cookies);
  }

  //例行省略....

  return result.build();
}

我们可以看到Request中是有CookieHandler的,通过client.getCookieHandler()函数获得了CookieHandler对象,通过该对象拿到cookie并设置到请求头里,请求结束后取得响应后通过networkResponse.headers()函数将请求头获得传入receiveHeaders函数,并将取得的cookie存入getCookieHandler得到的一个CookieHandler对象中去。那么我们可以这样加:

OkHttpClient client = new OkHttpClient();
client.setCookieHandler(CookieHandler cookieHanlder);

3.0之后: 3.0之后OKHttp是加了CookieJar和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);
  }

那么我们该怎么持久化管理呢?重点来了:

OkHttpClient client = new OkHttpClient.Builder()
    .cookieJar(new CookieJar() {
        private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            cookieStore.put(url, cookies);
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            List<Cookie> cookies = cookieStore.get(url);
            return cookies != null ? cookies : new ArrayList<Cookie>();
        }
    })
    .build();

上面的.addCookieJar就成功的帮我们将session和cookie放到了请求头里面,当调用了用户登录的接口之后,服务器接口的header里面的cookie和session我们就已经保存了。同时问题也来了,我们可以看出来并没有将cookie存到本地,也就是说当我们将APP关闭之后,如果你不再次调用登录接口就去直接调用别的接口,用户的cookie是错误的,服务器不识别你的当前用户,当然最笨的方法就是每次进入APP的时候都调用一下登录接口,这样也可以实现,但是…. 所以我的解决办法:

重点就在这: JavaNetCookieJar是CookieHandler的一个代理,它实现了CookieJar,我们可以看到它里面的loadForRequest()方法帮助我们从请求头里面获取了cookie并且通过saveFromResponse()保存了下来。

@Override public List<Cookie> loadForRequest(HttpUrl url) {
    // The RI passes all headers. We don't have 'em, so we don't pass 'em!
    Map<String, List<String>> headers = Collections.emptyMap();
    Map<String, List<String>> cookieHeaders;
    try {
      cookieHeaders = cookieHandler.get(url.uri(), headers);
    } catch (IOException e) {
      Internal.logger.log(WARNING, "Loading cookies failed for " + url.resolve("/..."), e);
      return Collections.emptyList();
    }

    List<Cookie> cookies = null;
    for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
      String key = entry.getKey();
      if (("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key))
          && !entry.getValue().isEmpty()) {
        for (String header : entry.getValue()) {
          if (cookies == null) cookies = new ArrayList<>();
          cookies.addAll(decodeHeaderAsJavaNetCookies(url, header));
        }
      }
    }

    return cookies != null
        ? Collections.unmodifiableList(cookies)
        : Collections.<Cookie>emptyList();
  }
@Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
    if (cookieHandler != null) {
      List<String> cookieStrings = new ArrayList<>();
      for (Cookie cookie : cookies) {
        cookieStrings.add(cookie.toString());
      }
      Map<String, List<String>> multimap = Collections.singletonMap("Set-Cookie", cookieStrings);
      try {
        cookieHandler.put(url.uri(), multimap);
      } catch (IOException e) {
        Internal.logger.log(WARNING, "Saving cookies failed for " + url.resolve("/..."), e);
      }
    }
  }

可以还是并没有实现本地保存啊,接着往下看:

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import java.io.*;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
 * Created by <a href="http://www.jiechic.com" target="_blank">jiechic</a> on 15/5/27.
 */
/**
 * A persistent cookie store which implements the Apache HttpClient CookieStore interface.
 * Cookies are stored and will persist on the user's device between application sessions since they
 * are serialized and stored in SharedPreferences. Instances of this class are
 * designed to be used with AsyncHttpClient#setCookieStore, but can also be used with a
 * regular old apache HttpClient/HttpContext if you prefer.
 */
public class PersistentCookieStore implements CookieStore {

    private static final String LOG_TAG = "PersistentCookieStore";
    private static final String COOKIE_PREFS = "CookiePrefsFile";
    private static final String COOKIE_NAME_PREFIX = "cookie_";

    private final HashMap<String, ConcurrentHashMap<String, HttpCookie>> cookies;
    private final SharedPreferences cookiePrefs;

    /**
     * Construct a persistent cookie store.
     *
     * @param context Context to attach cookie store to
     */
    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new HashMap<String, ConcurrentHashMap<String, HttpCookie>>();

        // Load any previously stored cookies into the store
        Map<String, ?> prefsMap = cookiePrefs.getAll();
        for(Map.Entry<String, ?> entry : prefsMap.entrySet()) {
            if (((String)entry.getValue()) != null && !((String)entry.getValue()).startsWith(COOKIE_NAME_PREFIX)) {
                String[] cookieNames = TextUtils.split((String)entry.getValue(), ",");
                for (String name : cookieNames) {
                    String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
                    if (encodedCookie != null) {
                        HttpCookie decodedCookie = decodeCookie(encodedCookie);
                        if (decodedCookie != null) {
                            if(!cookies.containsKey(entry.getKey()))
                                cookies.put(entry.getKey(), new ConcurrentHashMap<String, HttpCookie>());
                            cookies.get(entry.getKey()).put(name, decodedCookie);
                        }
                    }
                }

            }
        }
    }

    @Override
    public void add(URI uri, HttpCookie cookie) {

        // Save cookie into local store, or remove if expired
        if (!cookie.hasExpired()) {
            if(!cookies.containsKey(cookie.getDomain()))
                cookies.put(cookie.getDomain(), new ConcurrentHashMap<String, HttpCookie>());
            cookies.get(cookie.getDomain()).put(cookie.getName(), cookie);
        } else {
            if(cookies.containsKey(cookie.getDomain()))
                cookies.get(cookie.getDomain()).remove(cookie.getDomain());
        }

        // Save cookie into persistent store
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.putString(cookie.getDomain(), TextUtils.join(",", cookies.get(cookie.getDomain()).keySet()));
        prefsWriter.putString(COOKIE_NAME_PREFIX + cookie.getName(), encodeCookie(new SerializableHttpCookie(cookie)));
        prefsWriter.commit();
    }

    protected String getCookieToken(URI uri, HttpCookie cookie) {
        return cookie.getName() + cookie.getDomain();
    }

    @Override
    public List<HttpCookie> get(URI uri) {
        ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
        for (String key:cookies.keySet()){
            if (uri.getHost().contains(key)){
                ret.addAll(cookies.get(key).values());
            }
        }
        return ret;
    }

    @Override
    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.commit();
        cookies.clear();
        return true;
    }

    @Override
    public boolean remove(URI uri, HttpCookie cookie) {
        String name = getCookieToken(uri, cookie);

        if(cookies.containsKey(uri.getHost()) && cookies.get(uri.getHost()).containsKey(name)) {
            cookies.get(uri.getHost()).remove(name);

            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if(cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) {
                prefsWriter.remove(COOKIE_NAME_PREFIX + name);
            }
            prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
            prefsWriter.commit();

            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<HttpCookie> getCookies() {
        ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
        for (String key : cookies.keySet())
            ret.addAll(cookies.get(key).values());

        return ret;
    }

    @Override
    public List<URI> getURIs() {
        ArrayList<URI> ret = new ArrayList<URI>();
        for (String key : cookies.keySet())
            try {
                ret.add(new URI(key));
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

        return ret;
    }

    /**
     * Serializes Cookie object into String
     *
     * @param cookie cookie to be encoded, can be null
     * @return cookie encoded as 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());
    }

    /**
     * Returns cookie decoded from cookie string
     *
     * @param cookieString string of cookie as returned from http request
     * @return decoded cookie or null if exception occured
     */
    protected HttpCookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        HttpCookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
        } catch (IOException e) {
            Log.d(LOG_TAG, "IOException in decodeCookie", e);
        } catch (ClassNotFoundException e) {
            Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
        }

        return cookie;
    }

    /**
     * Using some super basic byte array <-> hex conversions so we don't have to rely on any
     * large Base64 libraries. Can be overridden if you like!
     *
     * @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);
    }

    /**
     * Converts hex values from strings to byte arra
     *
     * @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;
    }
}

我们自定义一个CookieStore来本地存储cookie,存储到SharedPreferences里。当然你也可以用这个: https://github.com/franmontiel/PersistentCookieJar 都是可以的,这样就完美实现了cookie的持久化管理。 下面是小编封装的一个网络请求类,不喜勿喷,哈哈:

推荐几篇这方面的资料,小编也是参考了一下资料:

http://stackoverflow.com/questions/34881775/automatic-cookie-handling-with-okhttp-3 http://www.open-open.com/lib/view/open1453422314105.html http://stackoverflow.com/questions/tagged/okhttp?sort=active

原文发布于微信公众号 - 非著名程序员(non-famous-coder)

原文发表时间:2016-05-10

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏everhad

设计模式:Builder

简介 建造者模式(Builder),将一个复杂对象的表示和它的构建分离,这样同样的构造过程可以创建出不同的对象状态。 类图 下面的Product是要创建的对象的...

18390
来自专栏Android开发与分享

【Android】DataBinding库(MVVM设计模式)

50470
来自专栏栗霖积跬步之旅

一天一个设计模式:适配器模式

适配器模式是把一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。

8530
来自专栏流媒体

Android平台下使用FFmpeg进行RTMP推流(视频文件推流)简介

前面已经讲到如何在Linux环境下编译FFmpeg以及在Android项目中使用,这一节就开始真正的使用FFmpeg。在Android平台下用FFmepg解析视...

78620
来自专栏Android开发指南

6.后台任务封装

29570
来自专栏不会写文章的程序员不是好厨师

Spring源码初探-IOC(5)-ApplicationContext功能扩展及其扩展点

前面几篇关于Spring的文章简单阐述了使用BeanFactory作为容器时bean的初始化过程。然而在实际使用中,我们并不会直接接触和编码BeanFactor...

13020
来自专栏技术小黑屋

关于Android Log的一些思考

在日常的Android开发中,日志打印是一项必不可少的操作,我们通过分析打印的日志可以分析程序的运行数据和情况。然而使用日志打印的正确姿势又是怎样呢,如何屏蔽日...

9210
来自专栏cmazxiaoma的架构师之路

FastDFS蛋疼的集群和负载均衡(十)之编写FastDFSUtil

23840
来自专栏青青天空树

安卓OKhttp请求封装

  目前安卓开发中使用的网络工具为OKhttp,但是okhttp的使用还不是很方便,在okhttp的基础上再对请求进行封装会极大的方便网络调用。

25530
来自专栏流媒体

MediaCodec进行AAC编解码(文件格式转换)

AAC,全称Advanced Audio Coding,是一种专为声音数据设计的文件压缩格式。与MP3不同,它采用了全新的算法进行编码,更加高效,具有更高的“性...

28150

扫码关注云+社区

领取腾讯云代金券