本文主要是介绍在WebView加载页面时添加cookies,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
场景:应用的登录界面是用android原生写的,登录成功后保存cookies到本地,然后需要用webview去加载某个页面,此时需要给webview添加本地保存的cookies,以避免二次登录.
我们可以在使用mWebView.loadUrl(url)之前给url添加上cookies,这样就可以避免重复登录问题了。
代码如下:
import java.util.List;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import com.lcoa.application.BaseApplication;
/*** 存储服务器返回的cookies* * @author zh* */
public class MyCookieStore {private static CookieSyncManager cookieSyncManager;public static CookieStore cookieStore = null;public static String JSESSIONID = null;public static String result = null;//在mWebView.loadUrl(url); 之前给url添加上cookiespublic static void setCookiesToURL(String url) {try {List<Cookie> cookies1 = MyCookieStore.cookieStore.getCookies();if (cookies1 != null && !cookies1.isEmpty()) {if (null == cookieSyncManager) {cookieSyncManager = CookieSyncManager.createInstance(BaseApplication.getApplication());}CookieManager cookieManager1 = CookieManager.getInstance();cookieManager1.setAcceptCookie(true);cookieManager1.removeSessionCookie();// 移除for (Cookie cookie1 : cookies1) {Cookie sessionInfo = cookie1;String cookieString = sessionInfo.getName() + "=" + JSESSIONID + ";";cookieSyncManager.startSync();new Thread().sleep(500);// 刷新 webview.db,不然不会得到实时效果cookieManager1.setCookie(url, cookieString);}String cook = cookieManager1.getCookie(url);System.out.println("getCookie: -----------" + cook);}} catch (Exception e) {e.printStackTrace();}}
}
这篇关于在WebView加载页面时添加cookies的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!