将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();