Android上的HttpClient不会保持会话

时间:2012-05-08 14:55:00

标签: android httpclient

我一直在尝试在不同的活动中使用相同的HttpClient实例,但它无法正常工作。所以我决定尝试一个活动并使用HttpClient登录,然后在登录成功后注销。这一切都在同一个活动中,所以HttpClient肯定会保持会话正确吗?

HttpClient client = new DefaultHttpClient();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair(UN_ID, username));
    postParameters.add(new BasicNameValuePair(PW_ID, password));

HttpPost request = new HttpPost(URL);

formEntity = new UrlEncodedFormEntity(postParameters);

request.setEntity(formEntity);

response = client.execute(request);

如果响应成功登录,我会尝试注销:

if (responseCode.equals("101")){ //successful
        HttpGet g = new HttpGet("https://site.com/file.php?logout=1");
        HttpResponse r = client.execute(g);

这将返回“未登录”响应。这是服务器,HttpClient还是我的代码的问题?

编辑:回应Eric的回答。

我已经尝试过使用cookies:

CookieStore cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

然后更改了上面的每个回复以包含上下文:

response = client.execute(request, httpContext);

HttpResponse r = client.execute(g, httpContext);

1 个答案:

答案 0 :(得分:0)

这是因为默认情况下不会激活Cookie。您需要使用此问题中描述的HttpContext:How do I manage cookies with HttpClient in Android and/or Java?


讨论后编辑(见评论)

看起来错误来自身份验证过程的服务器实现问题