Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

android - Webview cannot accept cookies

I'm creating a WebView based Android app that enables the user to login onto a mobile operator. When I run the app the WebView opens the website but I get a message that the WebView doesn't allow cookies. I've tried various codes that I found here but none of them worked. Can anyone help me? Here is the code I'm using:

//in oncreate
final CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
final CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
String[] cookies = getCookie("https://myaccount.ee.co.uk/login-dispatch/?fa=register");
for (String cookie : cookies) {
    cookieManager.setCookie("https://myaccount.ee.co.uk/login-dispatch/?fa=register", cookie);
}
cookieSyncManager.sync();
webView.loadUrl("https://myaccount.ee.co.uk/login-dispatch/?fa=register");

and the getCookies method:

public String[] getCookie(String siteName) {
     CookieManager cookieManager = CookieManager.getInstance();
     String cookies = cookieManager.getCookie(siteName);
     String[] cookiesArray = cookies.split(";");
     return cookiesArray;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to override the shouldOverrideUrlLoading method to make your WebView handle all URL links, and not start a new browser on any link.

webview.setWebViewClient(new WebViewClient() {  
          @Override  
          public boolean shouldOverrideUrlLoading(WebView view, String url)  
          {  
            return false;  
          }  
});   

webview.loadUrl(url);

If this doesn't work you can replace your

cookieManager.setAcceptCookie(true);

to

cookieManager.setAcceptThirdPartyCookies(true);

because cookieManager.setAcceptCookie(true); doesn't work on Lollipop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...