本文介绍了如何在Android应用中使用HTTP cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试维护Android应用程序与Drupal网站之间的登录用户会话.在我的研究中,归结为将cookie发送回Drupal,但我正在努力实现它.我该如何开始呢?

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-在您的课程中定义CookieManager和CookieStore

1- Define CookieManager and CookieStore in your class

CookieManager cookieManager;
CookieStore cookieStore;

2-添加默认的Cookie处理程序,例如在类构造函数中或在OnCreate方法中

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

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

3-进行HTTP请求时使用cookie存储

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

这篇关于如何在Android应用中使用HTTP cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 10:35