response header 中拿到 Set-Cookie
然后保存到文件
String token = response.headers().get("Set-Cookie");
SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("token", token);
editor.apply();
每个请求都携带上 cookie
OkHttpClient okHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = new ArrayList<>();
SharedPreferences sp = context.getSharedPreferences("user", Context.MODE_PRIVATE);
String token = sp.getString("token", null);
if (token != null) {
Cookie cookie = Cookie.parse(url, token);
cookies.add(cookie);
}
return cookies;
}
}).build();
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BuildConfig.SERVER_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();