How to handle cookies in httpUrlConnection using cookieManager
Ok, the right way to do it is just like that:
Get Cookies from response header and load them into cookieManager:
static final String COOKIES_HEADER = "Set-Cookie";
HttpURLConnection connection = ... ;
static java.net.CookieManager msCookieManager = new java.net.CookieManager();
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));
}
}
Get Cookies from cookieManager and load them into connection:
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
// While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
connection.setRequestProperty("Cookie",
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
I've been searching/trying for days to fix my issue: cannot access protected web resources even after logging in successfully
I created the same app on iOS and didn't have the same problem because NSUrlConnection did the cookie maintenance for us behind the scene. On Android, I tried manually adding cookie
connection.setRequestProperty("Cookie", "PHPSESSID=str_from_server")
without any luck.
Finally I read this
and added the following 2 lines somewhere in the beginning of my app:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
and everything works fine now.