Retrofit+OkHttp实现Cookie持久化,RxJava方式
【摘要】
通过Interceptor实现cookie持久化,相关三方库:PersistentCookieJar
将cookie存储到本地
public class ReceivedCookiesIntercep...
通过Interceptor
实现cookie持久化,相关三方库:PersistentCookieJar
将cookie存储到本地
public class ReceivedCookiesInterceptor implements Interceptor {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers("set-cookie").isEmpty()) {
final StringBuffer cookieBuffer = new StringBuffer();
Observable.from(originalResponse.headers("set-cookie"))
.map(new Func1<String, String>() {
@Override
public String call(String s) {
String[] cookieArray = s.split(";");
return cookieArray[0];
}
})
.subscribe(new Action1<String>() {
@Override
public void call(String cookie) {
cookieBuffer.append(cookie).append(";");
}
});
SpUtil.setString(GlobalConstant.COOKIES, cookieBuffer.toString());
}
return originalResponse;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
将本地的cookie追加到http请求头中
public class AddCookiesInterceptor implements Interceptor {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
final Request.Builder builder = chain.request().newBuilder();
Observable.just(SpUtil.getString(GlobalConstant.COOKIES))
.subscribe(new Action1<String>() {
@Override
public void call(String cookie) {
//添加cookie
builder.addHeader("cookie", cookie);
}
});
return chain.proceed(builder.build());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
OkHttp配置
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(new ReceivedCookiesInterceptor())
.addInterceptor(new AddCookiesInterceptor())
.connectTimeout(15, TimeUnit.SECONDS)
.build();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
文章来源: blog.csdn.net,作者:yechaoa,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/yechaoa/article/details/80369924
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)