When my app starts up, I post a login request to a web service and receive a Cookie. I want to use that Cookie in my WebView, which I do with the following code:
List<Cookie> cookies = this.get_my_cookies_from_somewhere();
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
for (Cookie cookie : cookies) {
String rawUrl = (cookie.isSecure() ? "https" : "http") + "://" + cookie.getDomain() + cookie.getPath();
cookieManager.setCookie(rawUrl, cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain());
}
cookieSyncManager.sync();
Ideally, I would like to have the cookie url and "Set-Cookie" header value required by the CookieManager be built by the Cookie class or some utility class. Does such a thing exist?
I tried RFC2109Spec and RFC2965Spec, but they produce the "Cookie" header, not the "Set-Cookie" header.
The preferred method appears to be to send the Headers from your Response directly to the CookieManager. I'm basing this on code I found from Romain Guy:
final CookieManager cookieManager = CookieManager.getInstance();
final HttpResponse response = ...
final Header[] cookies = response.getHeaders("set-cookie");
for (Header cooky : cookies) {
cookieManager.setCookie(url, cooky.getValue());
}