1

Inside my service I run this code:

public class MainService extends Service {
....
....

  CookieManager mCookieManager = CookieManager.getInstance();
  CookieSyncManager mCookieSyncManager = CookieSyncManager.createInstance(mContext);
  if (mCookieSyncManager != null) {
     mCookieSyncManager.sync();
  }

  AsyncHttpClient myClient = new AsyncHttpClient();
  PersistentCookieStore myCookieStore = new PersistentCookieStore(mContext);
  myClient.setCookieStore(myCookieStore);
  myClient.setUserAgent("my service");

  myClient.get("http://example.com/mypage/", new AsyncHttpResponseHandler() {
    ...
  }
  ...
...
}

When I check my webserver logs, I can see cookies exists in request headers.
But these cookies are old cookies.

I also run this AndroidAsyncHttp code from an Activity. Same old cookies are sent.

But when I print out current cookies in my WebView, I see new cookies.

How can I send WebView's cookies with AndroidAsyncHttp ?

Stephane Landelle
  • 6,990
  • 2
  • 23
  • 29
trante
  • 33,518
  • 47
  • 192
  • 272

1 Answers1

2

Clear cookie before set the cookie

myCookieStore.clear();

In my experience I don't need that CookieManager. I only use this.

AsyncHttpClient myClient = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(mContext);
// clear cookie to make the fresh cookie, to ensure the newest cookie is being send
myCookieStore.clear();
// set the new cookie
myClient.setCookieStore(myCookieStore);
myClient.get("http://example.com/mypage/", new AsyncHttpResponseHandler() {
...
}
Gus Arik
  • 349
  • 2
  • 14
  • 1
    The problem is WebView and AsyncHttpClient uses different cookie storages. There is no connection between them, so AsyncHttpClient sends its own with HTTP request. – trante Jun 06 '14 at 05:58
  • This is a TOCTOU error without additional synchronization to keep your program from adding cookies to the store after you clear it, e.g. by concurrently handling a response with a `Set-Cookie` header. I dealt with a fair bit of pain before discovering this the hard way :) – breadmenace Dec 31 '20 at 01:31