维护本地CookieManager并手动写入与此Cookie Manager关联的Cookie存储最容易。
这段代码将Cookie从响应加载到Cookie管理器中:
/**
* Gets Cookies from the response header and loads them into cookie manager
*
* @param conn instance of {@link HttpURLConnection} object
* @param cookieManager the cookie manager({@link CookieManager} instance) in which the cookies are to be loaded
In case a null object is passed, the function will not perform any action and return back to the caller.
*/
public static void loadResponseCookies(@Nullable HttpURLConnection conn,@Nullable CookieManager cookieManager) {
//do nothing in case a null cokkie manager object is passed
if (cookieManager == null || conn == null){
return;
}
List cookiesHeader = conn.getHeaderFields().get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookieHeader : cookiesHeader) {
List cookies;
try {
cookies = HttpCookie.parse(cookieHeader);
} catch (NullPointerException e) {
log.warn(MessageFormat.format("{0} -- Null header for the cookie : {1}",conn.getURL().toString(), cookieHeader.toString()));