I encountered some pitfalls while implementing auto-login, so I’m writing this article to remind everyone not to get stuck in similar issues.
We all know that in web applications, cookies can be set and saved by the server. By default, cookies are cleared when the browser is closed, but the server can set the cookie’s expiration time, and the browser will automatically retain it. However, on Android, cookies are not automatically saved. I’m using OkHttp3, and I couldn’t find methods like response.addCookie(cookie) or request.getCookies() (which are used in Java web applications). If cookies aren’t saved and resent to the server, auto-login won’t work. It took me quite a while to realize that all this cookie handling is actually in the HTTP headers.
For OkHttp3, here’s how it works:

The logs show the cookies:

Once we’ve obtained the cookies through this method, the next step is to save them. I’ll write a static method to store the cookie in SharedPreferences, with the design principle of minimizing database operations.
public static final String ISLOGINED = "islogined";
public static final String COOKIE = "cookie";
public static void saveCookiePreference(Context context, String value) {
SharedPreferences preference = context.getSharedPreferences(ISLOGINED, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preference.edit();
editor.putString(COOKIE, value);
editor.apply();
}
Then call this method to save the cookie:

Next, write a method to retrieve the cookie value from SharedPreferences:
public static String getCookiePreference(Context context) {
SharedPreferences preference = context.getSharedPreferences(ISLOGINED, Context.MODE_PRIVATE);
String s = preference.getString(COOKIE, "");
return s;
}
Finally, the key step is to include the cookie in the HTTP headers for each request.

With this setup, auto-login should be successfully implemented.