OKHTTP Session(会话保持)
OkHttp不会自动保存session会话,需要我们手动去设置,代码如下
mOkHttpClient = new OkHttpClient.Builder()
//设置连接超时
.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
//设置cookie
.cookieJar(new CookManager())
.build();
在builder中设置cookieJar,但是cookieJar是个接口类,自定义一个CookManager类实现CookieJar接口.
public class CookManager implements CookieJar {
//这里一定一定一定是HashMap<String, List<Cookie>>,是String,不是url.
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
}
!!!!!注意注意注意!!!!!!
HashMap的key是String!!!!直接传进去url,是没有效果的!!!!!
如何持久化?
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//session持久化方法,保存session参数
for (Cookie cookie : cookies) {
Log.d(TAG, "saveFromResponse() called with: url = [" + url + "], cookies = [" + cookie + "]");
Log.d("CookManager", "saveFromResponse(CookManager.java:28): " + cookie.name());
Log.d("CookManager", "saveFromResponse(CookManager.java:28): " + cookie.value());
Log.d("CookManager", "saveFromResponse(CookManager.java:28): " + cookie.domain());
}
Cookie cookie =new Cookie.Builder()
.name("JSESSIONID")
.value("FA69B5065A28377813B58E91004472B7")
.path("/foundation/")
.domain("115.29.186.247")
.build();
cookies = new ArrayList<Cookie>();
cookies.add(cookie);
cookieStore.put(url.host(), cookies);
}
思路如上,保存Cookie基本参数,因业务不同而不同,如我的项目只需保存JSESSIONID,以及对应的值,path需要自己获取,domain不能为空,否则程序直接崩溃。在saveFromResponse方法中进行存储(本地存储),在loadForRequest中获取出来即可。