Search code examples
androidhttpcookie

How to add HttpCookies to GET and POST requests in android?


I am using HttpCookies to maintain online session on the server. On login, through a POST request, I am getting the cookies using the following code.

HttpPost  httpPost = new HttpPost(url);
CookieStore store =  ((DefaultHttpClient)client).getCookieStore();
        if(params != null)
            httpPost.setEntity(new UrlEncodedFormEntity(params));
        httpResponse = httpClient.execute(httpPost);

        cookies= httpClient.getCookieStore().getCookies();

        if(cookies.isEmpty())
        {
            Log.d("Cookies", "None!");
        }
        else
        {
            for (Cookie c : cookies) {
                Log.d("Cookies","Name ["+c.getName()+"] - Val ["+c.getValue()+"] - Domain ["+c.getDomain()+"] - Path ["+c.getPath()+"]");
                store.addCookie(c);
            }
        }

But the problem is, I am unable to attach the cookies in the next GET request, so as to maintain the session. I have tried the following code, but it's not working.

HttpContext ctx = new BasicHttpContext();
store.addCookie(singleCookie);
ctx.setAttribute(ClientContext.COOKIE_STORE, store);
Log.d("Servicehandler", singleCookie.getValue());
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse r_response = client.execute(request, ctx);

Solution

  • Well, I figured out the answer myself. There were different solutions posted in internet, but none of them mentioned things clearly, as I have no idea regarding backend development.

    In the following snippet, lets assume you retrieved a cookie (something like "w8rhn29wr208n4rc2mr29cmn2rn2m12", some random value) in last response. Now if you want to attach it to next request, you have to add it as HEADER in the request. The headers in a URL request is of the form "some_key=some_value". The "some_key" is actually defined in server side programming. For multiple cookies in same request, you have to attach multiple headers in the same request.

    Rest of the procedure is normal, about attaching the url, executing it and getting the response.

    String url= "www.test.in/test_cookie_link";
    HttpGet request = new HttpGet();
    //cookie_received_in_last_response = w8rhn29wr208n4rc2mr29cmn2rn2m12
    //add the cookie as header to the GET request
    request.addHeader("cookie","my_key=" + cookie_received_in_last_response);
    //attach the url to GET request
    request.setURI(new URI(url));
    //execute the request
    HttpResponse r_response = client.execute(request);