【发布时间】:2012-12-12 19:26:17
【问题描述】:
Android 中的 HttpClient 存在问题:通过使用以下代码,我想通过 webview 登录来使用之前已经设置的 cookie。所以登录数据应该在那里并且确实在那里,我测试了它。但是当我在 httppost 或 httpget 中使用 cookie 时,它不会使用登录数据。但这些 cookie 实际上应该足以接收需要登录的页面,不是吗?我不确定是否需要以特殊方式将 cookie 发送到服务器,或者是否足以将其加载到 httpcontext 中。代码如下:
DefaultHttpClient httpclient = new DefaultHttpClient();
CookieStore lCS = new BasicCookieStore();
if (CookieManager.getInstance().getCookie(pUrl) != null) {
String cookieString = CookieManager.getInstance().getCookie(pUrl);
String[] urlCookieArray = cookieString.split(";");
for (int i = 0; i < urlCookieArray.length; i++) {
System.out.println(urlCookieArray[i]);
String[] singleCookie = urlCookieArray[i].split("=");
Cookie urlCookie = new BasicClientCookie(singleCookie[0], singleCookie[1]);
lCS.addCookie(urlCookie);
}
}
HttpContext localContext = new BasicHttpContext();
httpclient.setCookieStore(lCS);
localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);
HttpPost httppost = new HttpPost(pUrl);
// get the url connection
try {
StringBuilder sb = new StringBuilder();
HttpResponse response = httpclient.execute(httppost, localContext);
InputStream is = response.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
如果我运行代码,我只会收到该网站的登录页面,所以它不接受 cookie。
提前感谢您的帮助
你好,提莫
【问题讨论】:
-
不,我不能。这正是我尝试过的。我什至尝试以这种方式设置标题。我唯一没有实现的是实体,因为实际上我没有要发布的数据(cookie 除外)。另一个帖子也没有帮助我:/
-
"我想使用之前通过webview登录的cookies" -- HttpClient使用的cookies独立于任何
WebView使用的cookies,如WebView不使用 HttpClient。
标签: java android cookies httpclient