问题
I use the Volley library for performing my app's requests. Now I really need to perform some operations following this order:
- A POST request using Volley library
- I receive a 204 response with a session cookie
- I need to set that cookie to be used with WebViews
I need to perform the first request with Volley because the response has a header containing the uri for the next request. Than I need to capture that header.
The problem is that I can not save the session cookie using the CookieManager
, because, as the doc says: "The cookie being set must not have expired and must not be a session cookie, otherwise it will be ignored.".
Is there a way to store that cookie for later uses with WebViews?
回答1:
Strangely enough, the documentation is either out of date or outright incorrect, it seems that the CookieManager
will save session cookies with no problems at all. (Here's the bug report)
This snippet works for me:
private void syncCookie(String domain, Cookie sessionCookie) {
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeSessionCookie();
String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
cookieManager.setCookie(domain, cookieString);
CookieSyncManager.getInstance().sync();
}
来源:https://stackoverflow.com/questions/25781951/storing-session-cookie-in-android-webkit-cookiemanager