Retrofit在客户端保持Cookie(服务器的Token验证)

Posted Anonymous-OS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Retrofit在客户端保持Cookie(服务器的Token验证)相关的知识,希望对你有一定的参考价值。


移动端项目和网站还是多多少少的区别的,拿这个用户登陆过期验证这个流程来说吧,一般的网站是不会做处理的,浏览器访问的时候会自动带有Cookie的,移动端这样处理就不行的,他是不会保存Cookie的,所以我们在做项目的时候,一般来说,服务器的哥们都会在登陆成功之后给你返回一个叫做Token的东西,其实就是验证授权,这个东西就像是SessionId,但是本质又不一样(目前能力理解)。这样,你用移动端每一次网络请求都把这个Token当做公共参数传递给服务器,这时候服务器会根据这个唯一的Token值拿到在redis缓存服务器中的缓存数据,然后给你提示。

这是一般的流程,我私下的一个项目,我没有去考虑这一点(外包,你懂得),所以出现了一个问题,就是我请求后台,后台出现了异常,说是Session过期,你妹的,我才刚登陆的成功啊,一下就反应过来这是为什么,因为后台的哥们用的是默认的Session,这个东西需要我们移动端自己去保持Cookie的。

我的项目用的是Retrofit+Rxjava,如何用Retrofit在客户端保持Cookie呢?


对于服务器做Session缓存的接口,移动端请求会返回一个Cookie的东西,可以打印看一下


我们需要保持的就是这个东东

先看一下okhttp的源码:


所以Retrofit可以利用okhttp本身是支持Cookie保持的特点来用设置okhttp作为Retrofit的底层请求框架,也可以自定义,根据情况而定,代码如下:

一、PersistentCookieStore 用来储存OkHttpCookies

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缓存到内存中 即map cookies
        Map<String, ?> prefsMap = cookiePrefs.getAll();
        for (Map.Entry<String, ?> entry : prefsMap.entrySet()) 
            String[] cookieNames = StringUtil.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缓存到内存中 如果缓存过期 就重置此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 OkHttpCookies(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(OkHttpCookies 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 = ((OkHttpCookies) 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;
    

二、需要实现序列化的 OkHttpCookies 用来持久OkHttpCookies

public class OkHttpCookies implements Serializable 

    private transient final Cookie cookies;
    private transient Cookie clientCookies;

    public OkHttpCookies(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();
    


三、实现有一个自定义的CookieManger来管理cookies,实现以K-V结构获取set,getCookier

public class CookieManger implements CookieJar 


    private static Context mContext;

    private static PersistentCookieStore cookieStore;

    public CookieManger(Context context) 

        mContext = context;
        if (cookieStore == null ) 
            cookieStore = new PersistentCookieStore(mContext);
        

    



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



四、Okhttp使用

public static RetrofitAPI Retrofit(Context mContext) 
	mHttpClient = new OkHttpClient().newBuilder()
			.connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
			.readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
			.writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间
			.addInterceptor(new LogInterceptor())//拦截器
			.cookieJar(new CookieManger(mContext))//cookie保持
			.build();
	if (retrofitAPI == null) 
		retrofitAPI = new Retrofit.Builder()
				.baseUrl("http://10.10.10.107/")
				.addConverterFactory(GsonConverterFactory.create())
				.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
				.client(mHttpClient)
				.build()
				.create(RetrofitAPI.class);
	
	return retrofitAPI;


五、持久化Cookie开源库,用了之后想骂人,为什么如此简单!


老样子,开源库嘛,肯定第一步就是引入依赖

compile 'com.github.franmontiel:PersistentCookieJar:v1.0.0'

如何使用:

ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));


OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .build();

相关文章:

开源库Git连接:

https://github.com/franmontiel/PersistentCookieJar



《码小白 CSDN博客》

小白大哥的博客写的很精髓,每次看都会有不同的灵感,没事也向他请教一些思路问题,真的很棒,分享一下。






以上是关于Retrofit在客户端保持Cookie(服务器的Token验证)的主要内容,如果未能解决你的问题,请参考以下文章

Retrofit 获取、设置cookie

Android Okhttp完美同步持久Cookie实现免登录

013-Cookie状态保持

HAProxy基于cookie实现客户端会话保持

会话保持之cookie session token

Session与Cookie