【发布时间】:2014-12-10 18:36:18
【问题描述】:
我正在尝试使用 cookie 在我的 Android 应用上保持会话,但我似乎遇到了问题,因为我从未收到来自服务器的预期响应。
起初我有一个登录例程,它按预期运行并返回所有预期数据。
我的登录请求:
HttpContext httpContext = new BasicHttpContext();
HttpResponse response;
HttpClient client = new DefaultHttpClient();
String url = context.getString(R.string.url_login);
HttpPost connection = new HttpPost(url);
connection.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair(PARAM_LOGIN,params[0]));
nameValuePair.add(new BasicNameValuePair(PARAM_PASSWORD,params[1]));
connection.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
response = client.execute(connection,httpContext);
data = EntityUtils.toString(response.getEntity());
在我做出回应后,我只是用数据做我需要的东西,然后事情就开始崩溃了。因为现在我只是想在同一个 AsyncTask 中调用我的服务器来测试我的 cookie 是否正确保存在我的 HttpContext 上。
一开始我只是调用了我的 URL,没有做任何更改,只是重用了我当前的 HttpContext:
HttpPost httpPost = new HttpPost(context.getString(R.string.url_cookie_test));
HttpResponse response = client.execute(httpPost, httpContext);
由于此测试失败,我测试了在我的 HttpPost 标头上添加我的 cookie 值:
httpPost.addHeader(context.getString(R.string.domain),PHPSESSID+"="+cookieID+";");
然后我尝试创建一个新的 HttpContext 并强制 COOKIE_STORE:
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie(PHPSESSID, cookieID);
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpResponse response;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(context.getString(R.string.url_cookie_test));
response = client.execute(connection,localContext);
一切都失败了,我已经确认,当我第一次收到登录响应时,我从 cookie 中获得了预期的数据,如下所示:
List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore().getCookies();
for (Cookie cookie: cookies){
Log.i("Cookie Value",cookie.toString());
/*
Prints:[[version: 0][name: PHPSESSID][value: 2ebbr87lsd9077m79n842hdgl3][domain: mydomain.org][path: /][expiry: null]]
*/
}
我已经在 StackOverflow 上进行了搜索,我发现了很多对我来说并不适用的解决方案,我将分享我已经尝试过的所有解决方案:
Android: Using Cookies in HTTP Post request
Sending cookie with http post android
Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request
【问题讨论】:
-
为什么不用 httpPost.setHeader("key","value") 而不是 addHeader 添加标题?我已经解决了这个更改的几个问题,它让我浪费了很多时间......我不知道是不是问题,但我认为值得证明
-
感谢您的建议,刚刚进行了测试,我一直得到相同的响应(cookie 不可用)。
-
我想我有一段代码可能对你有好处。它用于将 Android 连接到带有 cookie 的 Spring mvc 服务器,但我认为 tgat 也许它可以帮助你。我不介意与你分享。这不是你的答案,但让我帮你:)。我稍后会带着它来