The original question was: how do I prevent login each time after app start? Answer is of course to use cookies. So how do I store cookies so I can reuse after app restart?
The answer that works for me is very simple: just convert the cookiestore to a string, put it in the shared preferences before exiting the app. After the next app start, so before the next login, just get the sting from the shared preferences, convert it back to a cookiestore. Using the cookiestore prevents me logging in again.
public void saveCookieStore( CookieStore cookieStore) {
StringBuilder cookies = new StringBuilder();
for (final Cookie cookie : cookieStore.getCookies()) {
cookies.append(cookie.getName());
cookies.append('=');
cookies.append(cookie.getValue());
cookies.append('=');
cookies.append(cookie.getDomain());
cookies.append(';');
}
SharedPreferences.Editor edit = sharedPref.edit();
edit.putString( MY_GC_COOKIESTORE, cookies.toString());
edit.commit();
}
// retrieve the saved cookiestore from the shared pref
public CookieStore restoreCookieStore() {
String savedCookieString = sharedPref.getString( MY_GC_COOKIESTORE, null);
if( savedCookieString == null || savedCookieString.isEmpty()) {
return null;
}
CookieStore cookieStore = new BasicCookieStore();
for ( String cookie : StringUtils.split( savedCookieString, ';')) {
String[] split = StringUtils.split( cookie, "=", 3);
if( split.length == 3) {
BasicClientCookie newCookie = new BasicClientCookie( split[0], split[1]);
newCookie.setDomain( split[2]);
cookieStore.addCookie( newCookie);
}
}
return cookieStore;
}