android okHttp 中cookie的使用

通过拦截器的方式
public final static int CONNECT_TIMEOUT = 60;
public final static int READ_TIMEOUT = 100;
public final static int WRITE_TIMEOUT = 60;
private static OkHttpClient client = null;

private OkhttpUtils() {
}

public static OkHttpClient getInstance() {
    if (client == null) {
        synchronized (OkhttpUtils.class) {
            if (client == null)
                client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Response originalResponse = chain.proceed(chain.request());
                        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (String header : originalResponse.headers("Set-Cookie")) {
                                stringBuilder.append(header);
                            }
                            LogUtils.e("save" + stringBuilder.toString());
                            //把获取到的cookie存储到本地
                            SPUtils.getInstance().putString(SPConstants.COOKIE, stringBuilder.toString());
                        }
                        return originalResponse;
                    }
                })
                        .addInterceptor(new Interceptor() {
                            @Override
                            public okhttp3.Response intercept(Chain chain) throws IOException {
                                String cookie = SPUtils.getInstance().getString(SPConstants.COOKIE);
                                LogUtils.e("get" + cookie);
// 拿去请求
                                Request newRequest = chain.request().newBuilder()
                                        .header("Cookie", cookie != null ? cookie : "").build();
                                return chain.proceed(newRequest);
                            }
                        })
                        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                        .build();
        }
    }
    return client;
}

猜你喜欢

转载自blog.csdn.net/weixin_39738488/article/details/82498647