如何使用 cookieManager 处理 httpUrlConnection 中的 cookie [英] How to handle cookies in httpUrlConnection using cookieManager
本文介绍了如何使用 cookieManager 处理 httpUrlConnection 中的 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个返回多个 cookie 的服务器请求,如下所示:
I have a server request that returns multiple cookies, like that:
这是我将这些 cookie 存储到 cookieManager 的方式:
This is how I'm storing these cookies to the cookieManager:
HttpURLConnection connection = ... ;
static java.net.CookieManager msCookieManager = new java.net.CookieManager();
msCookieManager.put(COOKIES_URI, connection.getHeaderFields());
这是我将这些 cookie 添加到下一个连接的方式:
This is how I'm adding these cookies to the next connection:
connection.setRequestProperty("Cookie",
msCookieManager.getCookieStore().get(COOKIES_URI).toString());
这是从 cookieManager 中获取 cookie 的正确方法吗?,我很确定有更好的...
Is it the right way to get the cookies from the cookieManager?, I'm quite sure there is a better one...
推荐答案
好的,正确的做法是这样的:
Ok, the right way to do it is just like that:
从响应头中获取 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));
}
}
从 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()));
}
这篇关于如何使用 cookieManager 处理 httpUrlConnection 中的 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文