2

I am working on an Android app in which a log in post request is made to a webservice. The request returns a cookie which expires in 20 minutes.

Using okhttp3 and this PersistentCookieStore library, I got the cookie to be stored and subsequently added it as request header to access authentication-required get requests (e.g. personal information that are non-public).

The code goes this way,

CookieJar myCookieJar = new PersistentCookieJar(new SetCookieCache(), 
new SharedPrefsCookiePersistor(this));

OkHttpClient client = new OkHttpClient.Builder().cookieJar(HttpRequests.cookieJar).build();

I then call a method like this inside an (after I have gone through another log in Async task to get the cookie) Async task to perform a get request that requires authentication,

public static String PostReq(String url, String json) {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .addHeader("Cookie", "key=value")
            .post(body)
            .build();
    try (Response response = client.newCall(request).execute()) {
        return response.body().string();
    }
    catch(Exception e){

    }
}

The .addHeader("Cookie", "key=value") adds the cookie to the header to tell the webservice that I am authenticated.

Here comes my difficulty. Since the cookie expires after 20 minutes, I would like to be able to access the cookie itself to check for the expiration time and possibly redirect the user to the log in activity by calling the method,

myCookie.expiresAt() 

and comparing it to

System.currentTimeMillis()

I tried to look at the PersistentCookieStore codes and found that it uses a SharedPreference with the key "CookiePersistence". I looked inside this file while my emulator was running the app and found it to be empty however.

How would I be able to access this cookie that I have obtained? Much thanks for any advice to be given.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ronald D
  • 21
  • 1

1 Answers1

0

OK, this is old, but I was facing the same problem, and here is how I fixed it.

Hold a reference to your SetCookieCache used to instantiate your CookieJar:

SetCookieCache cookieCache = new SetCookieCache();
CookieJar myCookieJar = new PersistentCookieJar(
   cookieCache, 
   new SharedPrefsCookiePersistor(this)
);

Then use this to find your cookie and check it:

  for (Cookie cookie : cookieCache) {
     if (cookie.name().equals("cookie_name") && cookie.persistent()) {
        //cookie is still good
        break;
     }
  }

Or use cookie.expiresAt() to do your thing.

hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58