这是一段工作代码。
private void setCookie(DefaultHttpClient httpClient, String url) {
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
if (cookies != null) {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
String cookieString = cookie.getName() + "=" + cookie.getValue();
cookieManager.setCookie(url, cookieString);
}
CookieSyncManager.getInstance().sync();
}
}
这里的 httpclient 是您在 HttpGet/HttpPost 请求中使用的 DefaultHttpClient 对象。还要确保的一件事是 cookie 名称和值,应该给出
String cookieString = cookie.getName() + "=" + cookie.getValue();
setCookie 将为给定的 URL 设置 cookie。