HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Persistent cookie support using Volley and HttpUrlConnection

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
cookiepersistentusinghttpurlconnectionandvolleysupport

Problem

I need to add support for persistent cookies on an Android app that I'm building for Authentication/Authorization. This app uses Volley for making HTTP requests and its minSdkVersion is set to 9 (Gingerbread). Therefore Volley uses HttpUrlConnection internally.

What I had to do was create a new java.net.CookieStore that saves the incoming cookies to the SharedPreferences. I basically had similar requirements as this question.

I kind of merged java.net.CookieStoreImple with com.loopj.android.http.PersistentCookieStore and this little creature was created:

PersistentHttpCookieStore:

```
/**
* A shared preferences cookie store.
*/
final class PersistentHttpCookieStore implements CookieStore {
private static final String LOG_TAG = "PersistentHttpCookieStore";
private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_STORE = "names";
private static final String COOKIE_NAME_PREFIX = "cookie_";

/** this map may have null keys! */
private final Map> map;

private final SharedPreferences cookiePrefs;

/**
* Construct a persistent cookie store.
*
* @param context
* Context to attach cookie store to
*/
public PersistentHttpCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
map = new HashMap>();

// Load any previously stored cookies into the store
String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE,
null);
if (storedCookieNames != null) {
String[] cookieNames = TextUtils.split(storedCookieNames, ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX
+ name, null);
if (encodedCookie != null) {
HttpCookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie

Solution

A faster way of serialization is using DataOutputStream and DataInputStream. They are faster than ObjectOutputStream because they specifically handle primitive data types, and do not handle arbitrary data formats. In the case of cookies, that's all you need.

As part of that, instead of Serializable, consider using this SO answer's Packageable interface which wraps DataOutputStream and provides a convenient interface for it.

Context

StackExchange Code Review Q#61494, answer score: 3

Revisions (0)

No revisions yet.