Skip to content

Commit

Permalink
添加框架Cookie支持(支持非持久化Cookie和持久化Cookie)
Browse files Browse the repository at this point in the history
  • Loading branch information
谢杨 committed Jan 24, 2019
1 parent 80b9bb1 commit 5d61fdc
Show file tree
Hide file tree
Showing 12 changed files with 662 additions and 0 deletions.
2 changes: 2 additions & 0 deletions ApiDemo/src/main/java/com/api/demo/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ public void onCreate() {
DevRing.configureHttp()//配置retrofit
.setBaseUrl("https://api.douban.com/")//设置BaseUrl
.setConnectTimeout(15)//设置请求超时时长,单位秒
.setIsUseCookie(true)//是否开启Cookie
.setIsUseClearableCookieJar(false)//设置Cookie类型(true:持久化Cookie方式ClearableCookieJar,false:非持久化Cookie方式CookieManager)
// .setMapHeader(mapHeader)//设置全局的header信息
// .setIsUseCache(true)//设置是否启用缓存,默认不启用
// .setCacheFolder(file)//设置缓存地址,传入的file需为文件夹,默认保存在/storage/emulated/0/Android/data/com.xxx.xxx/cache/retrofit_http_cache下
Expand Down
3 changes: 3 additions & 0 deletions devring/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ dependencies {

//状态栏、导航栏颜色控制库
api 'com.github.zackratos.ultimatebar:ultimatebar3:3.1.1'

//JavaNetCookieJar来实现非持久化cookie
api 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'
}

//用于上传至Jcenter
Expand Down
18 changes: 18 additions & 0 deletions devring/src/main/java/com/ljy/devring/di/module/RingModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,16 @@
import com.ljy.devring.http.support.interceptor.HttpProgressInterceptor;
import com.ljy.devring.image.GlideManager;
import com.ljy.devring.image.support.IImageManager;
import com.ljy.devring.persistentcookiejar.ClearableCookieJar;
import com.ljy.devring.persistentcookiejar.PersistentCookieJar;
import com.ljy.devring.persistentcookiejar.cache.SetCookieCache;
import com.ljy.devring.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.ljy.devring.util.FileUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.List;
import java.util.concurrent.TimeUnit;

Expand All @@ -30,6 +36,7 @@
import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
Expand Down Expand Up @@ -124,6 +131,17 @@ OkHttpClient okHttpClient(Application application, OkHttpClient.Builder builder,
builder.cache(cache);
}

if (httpConfig.isUseCookie()) {
if (httpConfig.isUseClearableCookieJar()){
ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(application));
builder.cookieJar(cookieJar);
}else {
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
builder.cookieJar(new JavaNetCookieJar(cookieManager));
}
}

headerInterceptor.setMapHeader(httpConfig.getMapHeader());
if (!builder.interceptors().contains(headerInterceptor)) {
builder.addInterceptor(headerInterceptor);
Expand Down
22 changes: 22 additions & 0 deletions devring/src/main/java/com/ljy/devring/http/HttpConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public class HttpConfig {
private boolean mIsUseRetryWhenError;
private int mTimeRetryDelay= -1;
private int mMaxRetryCount;
private boolean mIsUseClearableCookieJar;
private boolean mIsUseCookie;

@Inject
public HttpConfig() {
Expand Down Expand Up @@ -159,6 +161,26 @@ public HttpConfig setMaxRetryCount(int maxRetryCount) {
return this;
}

public boolean isUseClearableCookieJar() {
return mIsUseClearableCookieJar;
}

//设置cookie
public HttpConfig setIsUseClearableCookieJar(boolean mIsUseClearableCookieJar) {
this.mIsUseClearableCookieJar = mIsUseClearableCookieJar;
return this;
}

//是否使用Cookie
public boolean isUseCookie() {
return mIsUseCookie;
}

public HttpConfig setIsUseCookie(boolean mIsUseCookie) {
this.mIsUseCookie = mIsUseCookie;
return this;
}

//获取builder进行你的个人定制
public OkHttpClient.Builder getOkHttpClientBuilder() {
return mOkHttpClientBuilder.get();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2016 Francisco José Montiel Navarro.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.ljy.devring.persistentcookiejar;

import okhttp3.CookieJar;

/**
* This interface extends {@link CookieJar} and adds methods to clear the cookies.
*/
public interface ClearableCookieJar extends CookieJar {

/**
* Clear all the session cookies while maintaining the persisted ones.
*/
void clearSession();

/**
* Clear all the cookies from persistence and from the cache.
*/
void clear();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright (C) 2016 Francisco José Montiel Navarro.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.ljy.devring.persistentcookiejar;

import com.ljy.devring.persistentcookiejar.cache.CookieCache;
import com.ljy.devring.persistentcookiejar.persistence.CookiePersistor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

public class PersistentCookieJar implements ClearableCookieJar {

private CookieCache cache;
private CookiePersistor persistor;

public PersistentCookieJar(CookieCache cache, CookiePersistor persistor) {
this.cache = cache;
this.persistor = persistor;

this.cache.addAll(persistor.loadAll());
}

@Override
synchronized public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cache.addAll(cookies);
persistor.saveAll(filterPersistentCookies(cookies));
}

private static List<Cookie> filterPersistentCookies(List<Cookie> cookies) {
List<Cookie> persistentCookies = new ArrayList<>();

for (Cookie cookie : cookies) {
if (cookie.persistent()) {
persistentCookies.add(cookie);
}
}
return persistentCookies;
}

@Override
synchronized public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookiesToRemove = new ArrayList<>();
List<Cookie> validCookies = new ArrayList<>();

for (Iterator<Cookie> it = cache.iterator(); it.hasNext(); ) {
Cookie currentCookie = it.next();

if (isCookieExpired(currentCookie)) {
cookiesToRemove.add(currentCookie);
it.remove();

} else if (currentCookie.matches(url)) {
validCookies.add(currentCookie);
}
}

persistor.removeAll(cookiesToRemove);

return validCookies;
}

private static boolean isCookieExpired(Cookie cookie) {
return cookie.expiresAt() < System.currentTimeMillis();
}

@Override
synchronized public void clearSession() {
cache.clear();
cache.addAll(persistor.loadAll());
}

@Override
synchronized public void clear() {
cache.clear();
persistor.clear();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright (C) 2016 Francisco José Montiel Navarro.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.ljy.devring.persistentcookiejar.cache;

import java.util.Collection;

import okhttp3.Cookie;

/**
* A CookieCache handles the volatile cookie session storage.
*/
public interface CookieCache extends Iterable<Cookie> {

/**
* Add all the new cookies to the session, existing cookies will be overwritten.
*
* @param cookies
*/
void addAll(Collection<Cookie> cookies);

/**
* Clear all the cookies from the session.
*/
void clear();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright (C) 2016 Francisco José Montiel Navarro.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.ljy.devring.persistentcookiejar.cache;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import okhttp3.Cookie;

/**
* This class decorates a Cookie to re-implements equals() and hashcode() methods in order to identify
* the cookie by the following attributes: name, domain, path, secure & hostOnly.<p>
*
* This new behaviour will be useful in determining when an already existing cookie in session must be overwritten.
*/
class IdentifiableCookie {

private Cookie cookie;

static List<IdentifiableCookie> decorateAll(Collection<Cookie> cookies) {
List<IdentifiableCookie> identifiableCookies = new ArrayList<>(cookies.size());
for (Cookie cookie : cookies) {
identifiableCookies.add(new IdentifiableCookie(cookie));
}
return identifiableCookies;
}

IdentifiableCookie(Cookie cookie) {
this.cookie = cookie;
}

Cookie getCookie() {
return cookie;
}

@Override
public boolean equals(Object other) {
if (!(other instanceof IdentifiableCookie)) return false;
IdentifiableCookie that = (IdentifiableCookie) other;
return that.cookie.name().equals(this.cookie.name())
&& that.cookie.domain().equals(this.cookie.domain())
&& that.cookie.path().equals(this.cookie.path())
&& that.cookie.secure() == this.cookie.secure()
&& that.cookie.hostOnly() == this.cookie.hostOnly();
}

@Override
public int hashCode() {
int hash = 17;
hash = 31 * hash + cookie.name().hashCode();
hash = 31 * hash + cookie.domain().hashCode();
hash = 31 * hash + cookie.path().hashCode();
hash = 31 * hash + (cookie.secure() ? 0 : 1);
hash = 31 * hash + (cookie.hostOnly() ? 0 : 1);
return hash;
}
}
Loading

0 comments on commit 5d61fdc

Please sign in to comment.