retrofit2.0 cookie 的持久化

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 cookies) {

   }

   @Override
   public List loadForRequest(HttpUrl url) {
       List 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();

你可能感兴趣的:(retrofit2.0 cookie 的持久化)