VM 范围的 cookie 管理是什么意思?

What does it mean by VM wide cookie management?

我正在学习将 cookies 存储在 Android 中,并且遇到了几种实现它的方法。其中之一是使用 CookieManager and CookieStore.

当我浏览 Android 文档时,我遇到了以下声明:

To establish and maintain a potentially long-lived session between client and server, HttpURLConnection includes an extensible cookie manager. Enable VM-wide cookie management using CookieHandler and CookieManager:

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

我不明白VM-wide cookie management的意思。我知道 VM 的意思是 Virtual Machine.

我的解读:

  1. 我对它的一种解释是,创建一个 CookieManager 并将其传递给 setDefault() 使其在整个应用程序中可用。因此,我尝试了以下测试。

     URL url = new URL("http://something.com");
     URI uri=new URI("http://something.com");
     urlConnection = (HttpURLConnection) url.openConnection();
     cks=urlConnection.getHeaderField("Set-Cookie");  
     //cks is a String
     cookieManager=new CookieManager();
     CookieHandler.setDefault(cookieManager);
     HttpCookie hc=new HttpCookie("Cookie1",cks);
     cookieManager.getCookieStore().add(uri,hc);
     cks1=cookieManager.getCookieStore().getCookies().get(0).getValue();
     //cks1 is another String
    

    我将 cks and cks1 设置为 TextViews,它按预期打印了 cookie content/value。根据我的解释,我在另一个 activity 中尝试了 cookieManager.getCookieStore().getCookies().get(0).getValue(); 但它无法识别该对象,这意味着它超出范围且无法访问。此外,创建了一个新的 CookieManager 并尝试获取 cookie,但它返回了 null。因此,我认为这种跨活动可访问 VM 范围的解释是不正确的。

  2. 第二种解释是设置CookieManager时会自动存储Cookies。我从另一个问题的解决方案中得到它:

解决方案中的陈述之一是这样建议的:

When HttpURLConnection receives a cookie from the server the CookieManager will receive the cookie and store it. Future requests to the same server will automatically send the previously set cookies.

我删除了 cookieManager.getCookieStore().add(uri,hc); 来测试它,发现 cookie 不会自动存储。所以,这种解释也失败了。

另一个困扰我的问题:

大多数存储 cookie 供以后使用的解决方案建议使用 SharedPreferences。困扰我的是,它们最初都将 cookie 存储在 CookieManager 中,然后将其移动到 SharedPreferences。为什么不直接用SharedPreferences呢?

例如:

URL url = new URL("http://something.com");
 urlConnection = (HttpURLConnection) url.openConnection();
 cks=urlConnection.getHeaderField("Set-Cookie"); 
 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
 Editor editor = pref.edit();
 editor.putString("cookie_name", cks);  // Saving cookie
 editor.commit();

那么使用 CookieManager 然后将其移动到 SharedPreferences 有什么意义呢?

可以找到有关 Android 的 cookie 管理框架的更多详细信息 in this doc, but in short, you only need to setDefault() once. In subsequent calls you can use CookieHandler.getDefault() and you supply the cookies to the sessions as demonstrated in this answer

使用默认实现,您将只能从您自己的应用程序访问 cookie。

用最简单的术语来说,Android VM 是将您的应用程序字节码转换为机器代码的层,每个应用程序一个 VM - 因此 VM-Wide 表示应用程序范围。

SharedPrefs 可用于在会话之间保留 cookie,尽管这应该很少有用(只是我的意见)