乐闻世界logo
搜索文章和话题

How to set cookie in android WebView client

1个答案

1

Setting cookies in an Android WebView client typically involves the following steps:

  1. Obtain the CookieManager instance: CookieManager is a singleton class used for managing cookies within a WebView. You can obtain its instance using CookieManager.getInstance().

  2. 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.

  3. 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:

  • myWebView refers 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.

2024年6月29日 12:07 回复

你的答案