7

我对 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。

提前感谢您的帮助

问候,蒂莫

4

3 回答 3

8

I had the same problem and I used similar approach as in the question with no luck. The thing that made it work for me was to add the domain for each copied cookie. (BasicClientCookie cookie.setDomain(String))

My util function:

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);
 ...
于 2013-04-10T11:46:52.803 回答
1

如果您仍然遇到此问题,请注意给定的 cookie,有些可能格式不正确,请检查以下两个站点:

http://www.codeproject.com/Articles/3106/On-The-Care-and-Handling-of-Cookies

这个帮助了我: 获取“Set-Cookie”标头

于 2013-08-03T23:49:12.780 回答
0

看来您正在正确复制 cookie,通常您不需要为 HttpClient 执行任何特殊操作来发送 cookie。但是,其中一些可能绑定到会话,并且当您打开与 HttpClient 的新连接时,您会打开一个新会话。服务器可能会忽略与当前会话不匹配的 cookie。如果会话 ID 在 cookie 中并且您能够进入同一个会话,这可能会起作用,但您确实需要确切地知道服务器在做什么。

于 2012-12-13T03:59:28.553 回答