Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Retrofit+OKHttp 教你怎麼持久化管理Cookie

Retrofit+OKHttp 教你怎麼持久化管理Cookie

編輯:關於Android編程

緒論

今天小編來給大家分享點什麼呢?對,就是它:Retrofit,話說Retrofit最近真的很火啊,Retrofit+OKHttp現在似乎已經成為了Android網絡請求框架的主流框架了吧,小編之前用的是XUtils框架,個人感覺也不錯,也更新到了Xutils3,但是畢竟Retrofit是Square出的,所以小編還是忍不住需要探索一下。
鑒於現在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> headers = OkHeaders.toMultimap(result.build().headers(), null);

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

那麼我們該怎麼持久化管理呢?重點來了:

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

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

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

上面的.addCookieJar就成功的幫我們將session和cookie放到了請求頭裡面,當調用了用戶登錄的接口之後,服務器接口的header裡面的cookie和session我們就已經保存了。同時問題也來了,我們可以看出來並沒有將cookie存到本地,也就是說當我們將APP關閉之後,如果你不再次調用登錄接口就去直接調用別的接口,用戶的cookie是錯誤的,服務器不識別你的當前用戶,當然最笨的方法就是每次進入APP的時候都調用一下登錄接口,這樣也可以實現,但是….
所以我的解決辦法:

這裡寫圖片描述
重點就在這:
JavaNetCookieJar是CookieHandler的一個代理,它實現了CookieJar,我們可以看到它裡面的loadForRequest()方法幫助我們從請求頭裡面獲取了cookie並且通過saveFromResponse()保存了下來。

@Override public List loadForRequest(HttpUrl url) {
    // The RI passes all headers. We don't have 'em, so we don't pass 'em!
    Map> headers = Collections.emptyMap();
    Map> 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 cookies = null;
    for (Map.Entry> 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.emptyList();
  }
@Override public void saveFromResponse(HttpUrl url, List cookies) {
    if (cookieHandler != null) {
      List cookieStrings = new ArrayList<>();
      for (Cookie cookie : cookies) {
        cookieStrings.add(cookie.toString());
      }
      Map> 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 jiechic 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> 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>();

        // Load any previously stored cookies into the store
        Map prefsMap = cookiePrefs.getAll();
        for(Map.Entry 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());
                            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());
            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 get(URI uri) {
        ArrayList ret = new ArrayList();
        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 getCookies() {
        ArrayList ret = new ArrayList();
        for (String key : cookies.keySet())
            ret.addAll(cookies.get(key).values());

        return ret;
    }

    @Override
    public List getURIs() {
        ArrayList ret = new ArrayList();
        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的持久化管理。
下面是小編封裝的一個網絡請求類,不喜勿噴,哈哈:


import android.content.Context;

import com.hankkin.bpm.Constant;
import com.hankkin.bpm.http.cookie.PersistentCookieStore;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.internal.JavaNetCookieJar;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Hankkin on 16/4/25.
 */
public class HttpControl {

    private static HttpControl mInstance;
    private Retrofit retrofit;

    public static HttpControl getInstance(Context context){
        if (mInstance == null){
            synchronized (HttpControl.class){
                if (mInstance == null)
                    mInstance = new HttpControl(context);
            }
        }
        return mInstance;
    }
    public HttpControl(Context context){

        CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(context),
                CookiePolicy.ACCEPT_ALL);


        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);



        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(7676, TimeUnit.MILLISECONDS)
                .connectTimeout(7676,TimeUnit.MILLISECONDS)
                .addInterceptor(logging)
                .cookieJar(new JavaNetCookieJar(cookieHandler))
                .build();


        retrofit = new Retrofit.Builder().
                baseUrl(Constant.BASE_URL).
                addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
    }



    public   T createService(Class clz){
        return retrofit.create(clz);
    }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved