sisko
sisko

Reputation: 9900

How to use HTTP cookies in an Android app?

I am trying to maintain a logged-in user session between my Android app and my Drupal website. In my research, it comes down to sending cookie(s) back to Drupal but I am struggling to implement it. How can I make a start on this?

Upvotes: 1

Views: 847

Answers (2)

iTech
iTech

Reputation: 18440

Just in case anyone else got the same issue, I had similar problem and I was able to solve it by the following code:

1- Define CookieManager and CookieStore in your class

CookieManager cookieManager;
CookieStore cookieStore;

2- Add default cookie handler, e.g. in the class constructor or in OnCreate method

cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

3- Use the cookie storage when you do HTTP request

public byte[] openURI(String uri) {

    try {
        URI uriObj = new URI(uri);
        DefaultHttpClient client = new DefaultHttpClient();

        // Use the cookieStor with the request
        if (cookieStore == null) {
            cookieStore = client.getCookieStore();
        } else {
            client.setCookieStore(cookieStore);
        }

        HttpGet getRequest = new HttpGet(uriObj);
        HttpResponse response = client.execute(getRequest);

        // Read the response data
                    InputStream instream = response.getEntity().getContent();
        int contentLength = (int) response.getEntity().getContentLength();
        byte[] data = new byte[contentLength];
        instream.read(data);
        response.getEntity().consumeContent();
        return data ;

    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;        
}

Upvotes: 1

Shardul Upadhyay
Shardul Upadhyay

Reputation: 417

I am pretty sure that if you use the HttpClient provided with the Android APIs it should do session management with cookies for you until you close the connection manually.

If I am wrong on this, then you can easily work around this by implementing your own cookie store using the CookieStore interface or the BasicCookieStore class. If all else fails, you can store cookies manually and set cookies in the header each time you make a HTTP request.

I am not sure how this might change for your particular problem though but this should most likely work considering the description of the problem you gave.

Upvotes: 0

Related Questions