如何在Android应用中使用HTTP cookie?

| 我正在尝试维护我的Android应用程序和Drupal网站之间的登录用户会话。在我的研究中,归结为将cookie发送回Drupal,但我正在努力实现它。我该如何开始呢?     
已邀请:
        万一其他人遇到相同的问题,我也遇到类似的问题,我可以通过以下代码解决它: 1-在您的课程中定义CookieManager和CookieStore
CookieManager cookieManager;
CookieStore cookieStore;
2-添加默认的Cookie处理程序,例如在类构造函数中或在OnCreate方法中
cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
3-当您执行HTTP请求时使用cookie存储
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 API随附的HttpClient,它将在您手动关闭连接之前为您执行cookie会话管理。 如果我错了,那么可以通过使用CookieStore接口或BasicCookieStore类实现自己的cookie存储,轻松解决此问题。如果所有其他方法均失败,则可以手动存储cookie,并在每次发出HTTP请求时在标题中设置cookie。 我不确定这是否会针对您的特定问题而改变,但是考虑到您对问题的描述,这很可能会起作用。     

要回复问题请先登录注册