我使用来自android.webkit.CookieManager - https://developer.android.com/reference/android/webkit/CookieManager.html的android.webkit.CookieManager-https://developer.android.com/reference/android/webkit/CookieManager.html方法为两个不同的URL设置了两个cookie,其值相同。
但是,我知道当我在webview上加载第一个URL时,它会向我发送一个HTTP重定向到我也设置了cookie的第二个URL。
我的问题是: cookie管理器会为第二个URL发送cookie吗?
发布于 2018-05-16 16:34:51
是。
只要cookie满足需求(域、路径、安全、httponly、未过期等)然后,WebView将与每个请求一起发送cookie。这包括当WebView请求重定向URL时,如果有满足重定向URL要求的cookie,则WebView将与请求一起发送这些cookie。因此,如果您显式地为重定向URL设置了cookie,那么当WebView遵循重定向并请求重定向URL时,就应该包含它。
示例1
使用android.webkit.CookieManager设置所有WebView实例将使用的cookie。我通常在活动的onCreate()方法或片段的onViewCreated()方法中这样做,但是您可以在几乎任何生命周期方法中配置CookieManager,但是它必须在WebView加载url之前完成。这是在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
如果您知道重定向URL将位于相同的顶点域,例如。mydomain.com将重定向到redirect.mydomain.com,或者www.mydomain.com将重定向到subdomain.mydomain.com,或者subdomain.mydomain.com将重定向到mydomain.com,然后,您可以为整个域设置一个cookie E 226。
@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);
}https://stackoverflow.com/questions/46676779
复制相似问题