Setting cookies in an Android WebView client typically involves the following steps:
-
Obtain the CookieManager instance: CookieManager is a singleton class used for managing cookies within a WebView. You can obtain its instance using
CookieManager.getInstance(). -
Configure the cookie acceptance policy: By default, WebView automatically accepts third-party cookies. However, you can use the
CookieManager.setAcceptThirdPartyCookies()method to modify this behavior. -
Set specific cookies: You can set cookies for a specific URL using the
CookieManager.setCookie()method.
Here is a simple example demonstrating how to set cookies for a specific website within a WebView client:
java// Obtain the WebView's CookieManager instance CookieManager cookieManager = CookieManager.getInstance(); // Enable Cookies cookieManager.setAcceptCookie(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // For Lollipop and above, WebView defaults to not accepting cross-site cookies, so set it cookieManager.setAcceptThirdPartyCookies(myWebView, true); } // Set Cookie String url = "https://www.example.com"; // The URL your WebView will access String cookieString = "cookie_name=cookie_value; path=/"; // The cookie you want to set, formatted according to HTTP standards cookieManager.setCookie(url, cookieString); // Ensure synchronization to WebView if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { CookieSyncManager.getInstance().sync(); } else { cookieManager.flush(); } // Now load your WebView myWebView.loadUrl(url);
Note:
myWebViewrefers to your WebView instance.- Starting from Android 5.0 (API level 21), the CookieManager instance synchronizes automatically without requiring CookieSyncManager; use the
flush()method to ensure all cookies are written to disk.
In practical applications, you should verify the validity of the URL and cookies, ensuring they comply with HTTP standards, and confirm that WebView's internet permissions are enabled before setting cookies.