Java – Android: Use cookies in HTTP Post requests

Android: Use cookies in HTTP Post requests… here is a solution to the problem.

Android: Use cookies in HTTP Post requests

I’m having some issues authenticating with my server.

When I try to set cookies manually via a Google plugin like Postman, it works, but when it’s done through an android device or emulator, it doesn’t work.

Here is my part of the code :

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); 

Here is my reply in 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>

Am I doing something wrong? I also tried setting ci_session into header, but again it didn’t work. Please advise. Thanks!

Solution

Are you sure the cookie is set correctly?
In my case, I use HttpGet and set cookies manually:

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

Cookies are stored in sharedPreferences. Should work for HttpPost as I think.

Related Problems and Solutions