使用HttpURLConnection 如何获取多个SetCookie
使用con.getHeaderField("Set-Cookie");只能获取最后一个Set-Cookie求解...
使用con.getHeaderField("Set-Cookie");
只能获取最后一个Set-Cookie
求解 展开
只能获取最后一个Set-Cookie
求解 展开
3个回答
2015-06-12 · 知道合伙人互联网行家
关注
展开全部
1. 在app启动的时候,设置一个cookiemanager的实例
写在APP的oncreate里面:
CookieSyncManager.createInstance(this);
2. 设置,获取
protected String getCookie() {
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie("cookie");
if (cookie != null) {
return cookie;
} else {
return "";
}
}
protected void setCookie(String cookie) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie("cookie", cookie);
}
3. 过期按需处理一下
附1:cookie的获取
response.headerFields = conn.getHeaderFields();
setCookies(response.headerFields);
/**
* 存储cookie
* @param headerFields
*/
protected void setCookies(Map<String, List<String>> headerFields) {
if (null == headerFields) {
return;
}
List<String> cookies = headerFields.get(COOKIES_KEY);
if (null == cookies) {
return;
}
for (String cookie : cookies) {
setCookie(cookie);
}
}
COOKIE_KEY="Set-Cookie"
写在APP的oncreate里面:
CookieSyncManager.createInstance(this);
2. 设置,获取
protected String getCookie() {
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie("cookie");
if (cookie != null) {
return cookie;
} else {
return "";
}
}
protected void setCookie(String cookie) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie("cookie", cookie);
}
3. 过期按需处理一下
附1:cookie的获取
response.headerFields = conn.getHeaderFields();
setCookies(response.headerFields);
/**
* 存储cookie
* @param headerFields
*/
protected void setCookies(Map<String, List<String>> headerFields) {
if (null == headerFields) {
return;
}
List<String> cookies = headerFields.get(COOKIES_KEY);
if (null == cookies) {
return;
}
for (String cookie : cookies) {
setCookie(cookie);
}
}
COOKIE_KEY="Set-Cookie"
展开全部
String cookieVal = null;
String key=null;
for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++ ) {
if (key.equalsIgnoreCase("set-cookie")) {
cookieVal = http.getHeaderField(i);
cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
sessionId=sessionId+cookieVal+";";
}
}
String key=null;
for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++ ) {
if (key.equalsIgnoreCase("set-cookie")) {
cookieVal = http.getHeaderField(i);
cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
sessionId=sessionId+cookieVal+";";
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
getHeaderFields 返回的MAP 自己处理
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询