如何使用cookieManager在httpUrlConnection中处理cookie

我有一个服务器请求,返回多个cookie,如下所示:


这就是我将这些cookie存储到cookieManager的方式:


HttpURLConnection connection = ... ;

static java.net.CookieManager msCookieManager = new java.net.CookieManager();

msCookieManager.put(COOKIES_URI, connection.getHeaderFields());

这就是我将这些Cookie添加到下一个连接的方式:


connection.setRequestProperty("Cookie", 

  msCookieManager.getCookieStore().get(COOKIES_URI).toString());

是从cookieManager中获取cookie的正确方法吗?我很确定有更好的方法...


凤凰求蛊
浏览 1271回答 3
3回答

拉丁的传说

好的,正确的方法就是这样:从响应头获取Cookies并将其加载到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) {&nbsp; &nbsp; for (String cookie : cookiesHeader) {&nbsp; &nbsp; &nbsp; &nbsp; msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}从cookieManager获取Cookies并将它们加载到连接中:if (msCookieManager.getCookieStore().getCookies().size() > 0) {&nbsp; &nbsp; // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'&nbsp; &nbsp; connection.setRequestProperty("Cookie",&nbsp; &nbsp; TextUtils.join(";",&nbsp; msCookieManager.getCookieStore().getCookies()));&nbsp; &nbsp;&nbsp;}

喵喵时光机

我已经搜索/尝试了几天以解决我的问题:即使成功登录也无法访问受保护的Web资源我在iOS上创建了相同的应用程序,并且没有相同的问题,因为NSUrlConnection在后台为我们完成了cookie维护。在Android上,我尝试手动添加Cookieconnection.setRequestProperty("Cookie", "PHPSESSID=str_from_server")没有任何运气。最后我读到了并在应用程序的开头添加了以下两行:CookieManager cookieManager = new CookieManager();CookieHandler.setDefault(cookieManager);现在一切正常。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android