1. 程式人生 > >Retrofit+OkHttp實現Cookie持久化,RxJava方式

Retrofit+OkHttp實現Cookie持久化,RxJava方式

通過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; } }

將本地的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());
    }

}

OkHttp配置

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)

                .addInterceptor(new ReceivedCookiesInterceptor())
                .addInterceptor(new AddCookiesInterceptor())

                .connectTimeout(15, TimeUnit.SECONDS)
                .build();