我在Android中的HttpClient遇到问题:通过使用以下代码,我想使用通过Web视图登录之前已设置的cookie。因此,登录数据应该存在并且确实存在,我对此进行了测试。但是,当我在httppost或httpget中使用cookie时,它不使用登录数据。但是这些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添加域。(BasicClientCookie cookie.setDomain(String))
我的效用函数:
public static BasicCookieStore getCookieStore(String cookies, String domain) { String[] cookieValues = cookies.split(";"); BasicCookieStore cs = new BasicCookieStore(); BasicClientCookie cookie; for (int i = 0; i < cookieValues.length; i++) { String[] split = cookieValues[i].split("="); if (split.length == 2) cookie = new BasicClientCookie(split[0], split[1]); else cookie = new BasicClientCookie(split[0], null); cookie.setDomain(domain); cs.addCookie(cookie); } return cs; } String cookies = CookieManager.getInstance().getCookie(url); BasicCookieStore lCS = getCookieStore(cookies, MyApp.sDomain); HttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.setCookieStore(lCS); localContext.setAttribute(ClientContext.COOKIE_STORE, lCS); ...