Android CookieManager和重定向

时间:2017-10-10 22:06:46

标签: android android-webview http-redirect android-cookiemanager

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

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

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

1 个答案:

答案 0 :(得分:2)

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

示例1
使用android.webkit.CookieManager设置所有 WebView实例将使用的Cookie。我通常在我的Activity onCreate()方法或我的Fragment onViewCreated()方法中执行此操作,但您几乎可以在任何生命周期方法中配置CookieManager,但它必须WebView加载网址之前完成。这是在CookieManager中配置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
如果您知道重定向网址将位于同一顶点域中,例如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);

}