Retrofit2使用CookieJar存储cookie信息,首先创建CookieJar对象
public static final Map<String, List<Cookie>> cookieStore = new HashMap<>();
public static final CookieJar cookieJar = new CookieJar() {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
};
然后需要把cookieJar配置到OkHttpClient中
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(cookieJar).build();
最后把okHttpClient配置到Retrofit中
Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Config.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();