Android: using cookies in HTTP request

I am having trouble getting authenticated with my server.

It works when I manually try to set cookies via a google plugin like postman, but doesn't work when it's done via an Android device or emulator.

Here is my code for this part:

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

      

This is my answer 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 tried setting ci_session to headers as well, but similarly it didn't work. Please advise. Thank!

+3


source to share


2 answers


Are you sure the cookie is set correctly?
In my case, I am using HttpGet and manually setting the cookie:

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

      



The cookie is stored in sharedPreferences. Should work for HttpPost just as I think.

+2


source


I am having similar problems. You don't have to create a new one DefaultHttpClient

for every new request. Use static singleton code instead and use that for all your Http request requests.



+2


source







All Articles