Dav*_*vid 36 cookies android httpurlconnection android-cookiemanager
我有一个返回多个cookie的服务器请求,如下所示:

这就是我将这些cookie存储到cookieManager的方式:
HttpURLConnection connection = ... ;
static java.net.CookieManager msCookieManager = new java.net.CookieManager();
msCookieManager.put(COOKIES_URI, connection.getHeaderFields());
Run Code Online (Sandbox Code Playgroud)
这就是我将这些cookie添加到下一个连接的方式:
connection.setRequestProperty("Cookie",
msCookieManager.getCookieStore().get(COOKIES_URI).toString());
Run Code Online (Sandbox Code Playgroud)
它是从cookieManager获取cookie的正确方法吗?我很确定有一个更好的...
Dav*_*vid 102
好的,正确的方法是这样的:
从响应头获取Cookie并将其加载到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));
}
}
Run Code Online (Sandbox Code Playgroud)
从cookieManager获取Cookie并将其加载到连接中:
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()));
}
Run Code Online (Sandbox Code Playgroud)
Gol*_*umb 44
我一直在寻找/尝试几天来解决我的问题:即使在成功登录后也无法访问受保护的Web资源
我在iOS上创建了相同的应用程序并且没有相同的问题,因为NSUrlConnection在幕后为我们做了cookie维护.在Android上,我尝试手动添加cookie
connection.setRequestProperty("Cookie", "PHPSESSID=str_from_server")
Run Code Online (Sandbox Code Playgroud)
没有运气.
最后我读了这个
并在我的应用程序开头的某处添加了以下2行:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
Run Code Online (Sandbox Code Playgroud)
现在一切正常.
| 归档时间: |
|
| 查看次数: |
76607 次 |
| 最近记录: |