我一直在尝试在不同的活动中使用相同的 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 还是我的代码的问题?
编辑:回应埃里克的回答。
我已经用 cookie 试过了:
CookieStore cookieStore = new BasicCookieStore();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
然后更改上面的每个响应以包含上下文:
response = client.execute(request, httpContext);
HttpResponse r = client.execute(g, httpContext);