Android HTTP cookie

蓝咒 提交于 2019-12-11 07:39:43

问题


I am trying to maintain a loggedin 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 find a resource to help guide me.

Can anyone recommend a good tutorial that I can use to accomplish a cookie powered persistent connection between Android and Drupal, please?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6393252/android-http-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!