是的。
只要 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 之前完成。这是配置CookieManager
in的示例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);
}