Cookies似乎没有正确设置

时间:2013-05-23 05:44:20

标签: java android http cookies

我设法登录并获得有关会话的cookie。但是当我尝试发出新请求时,登录信息似乎丢失了(两个请求的HTML数据相同。第二个请求应该提供我的用户名和其他一些数据)。

我在发送新请求之前设置了这样的cookie(DefaultHttpClient实例是相同的):

    List<Cookie> cookies = httpclient.getCookieStore().getCookies();

    if(cookies != null)
    {
        for(Cookie cookie : cookies)
        {
            String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();  
            httppost.addHeader("Cookie",cookie.getName() + "=" + cookie.getValue() + ";");
            System.out.println(cookieString);
        }
    }  

    try
    {
        //System.out.println(httpclient.getCookieStore().getCookies());
        response = (BasicHttpResponse) httpclient.execute(httppost,localContext);
    }

我检查了cookie信息,似乎它返回了两个不同的“cookie-instances”(两个会话ID),我在上面的for循环中设置了它。但它仍然似乎没有用。 可能是什么问题?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

// Create a static instance of cookie store globally 

     cookieStore = new BasicCookieStore();

 // Create local HTTP context

    HttpContext localContext = new BasicHttpContext();

// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//execute your connection with context
  HttpResponse response = http.execute(post,localContext);


And then whenever you connect use that static cookie instance to connect
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, StaticInstance(cookieStore));
//and as usual
response = http.execute(post,localContext);