0

我正在使用 android.webkit.CookieManager 中的 setCookie 方法设置两个 cookie - https://developer.android.com/reference/android/webkit/CookieManager.html对两个不同的 URL 具有相同的值。

但是,我知道当我在 webview 上加载第一个 URL 时,它会向我发送一个 HTTP 重定向到我也设置了 cookie 的第二个 URL。

我的问题是:cookie 管理器会发送第二个 URL 的 cookie 吗?

4

1 回答 1

4

是的。

只要 cookie 满足要求(域、路径、安全、httponly、未过期等),WebView 就会随每个请求一起发送 cookie。这包括当 WebView 请求重定向 URL 时,如果存在满足重定向 URL 要求的 cookie,则 WebView 将连同请求一起发送这些 cookie。因此,如果您为重定向 URL 显式设置 cookie,那么当 WebView 跟随重定向并对重定向 URL 发出请求时,应该包含它。

示例 1
用于android.webkit.CookieManager设置所有 WebView实例都将使用的 cookie。我通常在我的 ActivityonCreate()方法或 FragmentonViewCreated()方法中执行此操作,但您可以CookieManager在几乎任何生命周期方法中配置,但必须WebView加载 url 之前完成。这是配置CookieManagerin的示例onViewCreated()

@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    //Replace R.id.webview with whatever ID you assigned to the WebView in your layout
    WebView webView = view.findViewById(R.id.webview);  

    CookieManager cookieManager = CookieManager.getInstance();

    //originalUrl is the URL you expect to generate a redirect
    cookieManager.setCookie(originalUrl, "cookieKey=cookieValue");

    //redirectUrl is the URL you expect to be redirected to
    cookieManager.setCookie(redirectUrl, "cookieKey=cookieValue");

    //Now have webView load the originalUrl. The WebView will automatically follow the redirect to redirectUrl and the CookieManager will provide all cookies that qualify for redirectUrl.
    webView.loadUrl(originalUrl);

}

示例 2
如果您知道重定向 URL 将在同一个顶级域中,例如。mydomain.com将重定向到redirect.mydomain.com,或www.mydomain.com将重定向到subdomain.mydomain.com,或subdomain.mydomain.com将重定向到mydomain.com,然后您可以为整个mydomain.com设置一个 cookie 。

@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    //Replace R.id.webview with whatever ID you assigned to the WebView in your layout
    WebView webView = view.findViewById(R.id.webview);  

    CookieManager cookieManager = CookieManager.getInstance();

    //Set the cookie for the entire domain - notice the use of a . ("dot") at the front of the domain
    cookieManager.setCookie(".mydomain.com", "cookieKey=cookieValue");

    //Now have webView load the original URL. The WebView will automatically follow the redirect to redirectUrl and the CookieManager will provide all cookies for the domain.
    webView.loadUrl(originalUrl);

}
于 2018-05-16T16:34:51.847 回答