通过对Retrofit2.0的<Retrofit 2.0 超能实践,完美支持Https传输>基础入门和案例实践,掌握了怎么样使用Retrofit访问网络,加入自定义header,包括加入SSL证书,基本的调试基础,但是正常的开发中会涉及cookie同步问题,可以实现一些自动或免登录登陆问题,接下来进入cookie同步姿势

Cookie

Cookies是一种能够让网站服务器把少量数据储存到客户端的硬盘或内存,或是从客户端的硬盘读取数据的一种技术。Cookies是当你浏览某网站时,由Web服务器置于你硬盘上的一个非常小的文本文件,它可以记录你的用户ID、密码、浏览过的网页、停留的时间等信息。当你再次来到该网站时,网站通过读取Cookies,得知你的相关信息,就可以做出相应的动作,如在页面显示欢迎你的标语,或者让你不用输入ID、密码就直接登录等等。

从本质上讲,它可以看作是你的身份证。但Cookies不能作为代码执行,也不会传送病毒,且为你所专有,并只能由提供它的服务器来读取。保存的信息片断以“名/值”对(name-value pairs)的形式储存,一个“名/值”对仅仅是一条命名的数据。一个网站只能取得它放在你的电脑中的信息,它无法从其它的Cookies文件中取得信息,也无法得到你的电脑上的其它任何东西。

Cookies中的内容大多数经过了加密处理,因此一般用户看来只是一些毫无意义的字母数字组合,只有服务器的CGI处理程序才知道它们真正的含义。

Cookie也是http的会话跟踪技术,也包含web端的session。cookie的作用就是为了解决HTTP协议无状态的缺陷所作的努力.

方式一:

自定义cookie

HttpClient中大家都知道加入cookie的方式

AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(MainActivity.this);
client.setCookieStore(myCookieStore);

因此Retrofit中需自我实现一个PersistentCookieStore 用来储存OkHttpCookies。

-PersistentCookieStore

/**
* Created by LIUYONGKUI on 2016-06-09.
*/
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 = 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);
}
}
}
}
} 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 用来持久OkHttpCookies

   /**
* Created by LIUYONGKUI on 2016-05-20.
*/
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

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

    public class CookieManger implements CookieJar {

public static String APP_PLATFORM = "app-platform";

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;
} static class Customer { private String userID;
private String token; public Customer(String userID, String token) {
this.userID = userID;
this.token = token;
} public String getUserID() {
return userID;
} public void setUserID(String userID) {
this.userID = userID;
} public String getToken() {
return token;
} public void setToken(String token) {
this.token = token;
} }

- Retrofit加入cookie

OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(
new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.cookieJar(new CookieManger(context))
.addInterceptor(loginInterceptor)
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build(); Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.build();

总结

实现加入cookies持久,实现免登陆基本步骤

1 实现可序列化的OkHttpcookies

2 实现储存OkHttpcookies的PersistentCookieStore

3 实现cookies管理工具CookieManger

4 构建OKHttpClient

5 Retrofit加入自定义的okHttpClient

6直接调用RetrofitClient

方式二:

方法一可能对某些网站不兼容,可以借助retfoit的拦截器实现

用来加入cookie

public class ReadCookiesInterceptor implements   Interceptor {

 @Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
HashSet<String> preferences = (HashSet) Preferences.getDefaultPreferences().getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
Log.v("OkHttp", "Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
} return chain.proceed(builder.build());
}

}

用来保存Cookies

public class SaveCookiesInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request()); if (!originalResponse.headers("Set-Cookie").isEmpty()) {
HashSet<String> cookies = new HashSet<>(); for (String header : originalResponse.headers("Set-Cookie")) {
cookies.add(header);
} Preferences.getDefaultPreferences().edit()
.putStringSet(Preferences.PREF_COOKIES, cookies)
.apply();
} return originalResponse;
}

}

okhttp

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(new ReadCookiesInterceptor());
okHttpClient.interceptors().add(new SaveCookiesInterceptor());

Retrofit

 Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.build();

Android Okhttp完美同步持久Cookie实现免登录的更多相关文章

  1. Retrofit2.0 ,OkHttp3完美同步持久Cookie实现免登录(二)

    原文出自csdn: http://blog.csdn.net/sk719887916/article/details/51700659: 通过对Retrofit2.0的<Retrofit 2.0 ...

  2. 通过设置PHPSESSID保存到cookie实现免登录

    $cookieParams = session_get_cookie_params(); session_set_cookie_params( 3600,// 设置sessionID在cookie中保 ...

  3. Retrofit 2.0 超能实践(一),okHttp完美支持Https传输

    http: //blog.csdn.net/sk719887916/article/details/51597816 Tamic首发 前阵子看到圈子里Retrofit 2.0,RxJava(Andro ...

  4. Android OkHttp的Cookie自己主动化管理

    Android中在使用OkHttp这个库的时候.有时候须要持久化Cookie,那么怎么实现呢.OkHttp的内部源代码过于复杂,不进行深究.这里仅仅看当中的HttpEngineer里面的部分源代码,在 ...

  5. Android OkHttp完全解析 --zz

    参考文章 https://github.com/square/okhttp http://square.github.io/okhttp/ 泡网OkHttp使用教程 Android OkHttp完全解 ...

  6. Android OkHttp完全解析 是时候来了解OkHttp了

    Android OkHttp完全解析 是时候来了解OkHttp了 标签: AndroidOkHttp 2015-08-24 15:36 316254人阅读 评论(306) 收藏 举报  分类: [an ...

  7. Android okHttp网络请求之Get/Post请求

    前言: 之前项目中一直使用的Xutils开源框架,从xutils 2.1.5版本使用到最近的xutils 3.0,使用起来也是蛮方便的,只不过最近想着完善一下app中使用的开源框架,由于Xutils里 ...

  8. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

  9. Android okHttp网络请求之文件上传下载

    前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...

随机推荐

  1. Option可选值(一)

    //: Playground - noun: a place where people can play import Cocoa class Person { var residence: Resi ...

  2. 同学们,OpenCV出3.0了,速去围观!

    OpenCV3.0 OpenCV > NEWS > OpenCV 3.0 2015-06-04 With a great pleasure and great relief OpenCV ...

  3. 离线安装 Chrome

    离线安装 Chrome 在这个帮助网页中最下面切换到中文 https://support.google.com/chrome/answer/95346 在网页的中上部点击 "离线安装 Chr ...

  4. spring mvc获取路径参数的几种方式

    一.从视图向controller传递值,  controller <--- 视图 1.通过@PathVariabl注解获取路径中传递参数 (参数会被复制到路径变量) @RequestMappin ...

  5. 25.Detours劫持技术

    Detours可以用来实现劫持,他是微软亚洲研究院开发出来的工具,要实现它首先需要安装Detours. 安装地址链接:https://pan.baidu.com/s/1eTolVZs 密码:uy8x ...

  6. MOOC使用心得

    1. Mooctest 使用心得 慕测平台是编程类考试和练习的服务平台,教师可以轻松监管考试流程,学生可以自由练习编程.系统负责编程练习的自动化评估及可视化展现,配合当下红火的MOOC慕课课程,慕测平 ...

  7. XTUOJ 1238 Segment Tree

    Segment Tree Accepted : 3 Submit : 21Time Limit : 9000 MS Memory Limit : 65536 KB Problem Descriptio ...

  8. 对比了解Grafana与Kibana的关键差异

    对比了解Grafana与Kibana的关键差异 http://www.infoq.com/cn/articles/grafana-vs-kibana-the-key-differences-to-kn ...

  9. 从头认识java-13.12 超类通配符

    这一章节我们来讨论一下超类通配符. 1.什么是超类通配符 在前一章节我们提到一种通配符,是使用<? extends XXX>来实现的,导致了后面的一系列问题,如今我们引入还有一种通配符-- ...

  10. 设计模式实例(Lua)笔记之六(Adapter模式)

    1.描写叙述 "我"在 2004 年的时候带了一个项目,做一个人力资源管理,该项目是我们总公司发起的项目,公司一共同拥有 700 多号人,包含子公司,这个项目还是比較简单的,分为三 ...