开发者

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜