Android:在HTTP Post请求中使用Cookie

时间:2013-02-19 08:57:40

标签: java android cookies httpclient

我在使用我的服务器进行身份验证时遇到了一些问题。

当我手动尝试通过像Postman这样的谷歌插件设置cookie但通过Android设备或模拟器完成时无效。

以下是该部分的代码:

String url = "www.thisismyendpoint.com";
String ci_session = "ci_session=token";

CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie stdCookie = new BasicClientCookie("Cookie",ci_session);
cookieStore.addCookie(stdCookie);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();

localContext.setAttribute(ClientContext.COOKIE_STORE,
        cookieStore);
HttpPost httppost = new HttpPost(url);

HttpResponse response = httpClient.execute(httppost, localContext); 

这是我在logcat中的回复:

02-19 16:43:47.149: D/response(27539): response: <div style="border:1px solid             #990000;padding-left:20px;margin:0 0 10px 0;">
02-19 16:43:47.149: D/response(27539): <h4>A PHP Error was encountered</h4>
02-19 16:43:47.149: D/response(27539): <p>Severity: Notice</p>
02-19 16:43:47.149: D/response(27539): <p>Message: Undefined index: ci_session</p>
02-19 16:43:47.149: D/response(27539): <p>Filename: controllers/test.php</p>
02-19 16:43:47.149: D/response(27539): <p>Line Number: 28</p>
02-19 16:43:47.149: D/response(27539): </div>

我做错了吗?我已经尝试将ci_session设置到标题中,但同样它也不起作用。请指教。谢谢!

2 个答案:

答案 0 :(得分:2)

我遇到了类似的问题。您不应为每个新请求创建新的DefaultHttpClient。相反,使用静态单例并将其用于满足您的所有Http请求。

答案 1 :(得分:2)

您确定Cookie设置正确吗? 就我而言,我使用HttpGet并手动设置cookie:

HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Cookie", cookie);

cookie存储在sharedPreferences中。应该像我想的那样为HttpPost工作。

相关问题