问题
I'm loading a website in Webview which uses some cookies to store session. I've written following lines to accept cookies
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
CookieManager.getInstance().setAcceptCookie(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.setAcceptFileSchemeCookies(true);
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
}
webView.loadUrl("https://www.irctc.co.in/nget/train-search");
At one stage (after payment from payment gateway), shouldOverrideUrlLoading
method is called and after that it's supposed to land to transaction success page but it keeps going to login page. This is my method:
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
Log.d(TAG, "The URL is loaded in webview itself");
return false;
}
Using Chrome Developer Tools, I can see following cookies for website
When I call method CookieManager.getInstance().getCookie(url)
I can see that the cookies JESESSIONID and SLB_Cookie are present in webview, but not sure about that Local storage cookie. Also, if I remove the Local storage cookie in Chrome, I'm getting the exact same page (login page) instead of transaction success page like WebView. So I think if by any means if I check whether the Local Storage cookie is present in webview or not, and if not present then if I add it, my job would be done. But I'm not able to achieve either of the task.
回答1:
If you want to pass your login users data to a cookie in Webview the do it like this The other day I had to pass my login object to particular URL as follow.
WebSettings settings = webViewRoi.getSettings();
settings.setDomStorageEnabled(true);
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
settings.setAppCacheEnabled(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowFileAccessFromFileURLs(true);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
FormsDTO formsDTO = new FormsDTO();
FormsDTOProfile dtoProfile = new FormsDTOProfile(LoginActivity.loginInfoDTO.getProfile());
formsDTO.setProfile(dtoProfile);
formsDTO.setAuthorized(true);
formsDTO.setToken(LoginActivity.loginInfoDTO.getToken());
String out123 = gson.toJson(formsDTO);
String auth2 = URLEncoder.encode(out123, "UTF-8");
String z = "userInfo=" + auth2; // here userinfo is the key of cookie
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url, z);
webViewRoi.setWebChromeClient(new WebChromeClient());
webViewRoi.loadUrl(url);
So if you know the key name of cookie then you can pass your login object through cookie. hope it helps you.
来源:https://stackoverflow.com/questions/52686044/webview-not-accepting-some-cookies