Android WebView HTTP Cookies not working in API 21

◇◆丶佛笑我妖孽 提交于 2020-01-01 03:21:12

问题


I have an Android application that uses WebView and HTTP cookies. This application works on Android devices running API 19 or below. API 21 is not saving the http cookie for later reference.

Android WebView Code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_token);
    WebView mWebView = (WebView) findViewById(R.id.activity_main_webView1);
    mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    mWebView.setWebViewClient(new WebViewClient());
    mWebView.setWebChromeClient(new WebChromeClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            return false;
        }
    });
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setGeolocationEnabled(true);
    mWebView.getSettings().setAppCacheEnabled(true);
    mWebView.getSettings().setDatabaseEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    mWebView.loadUrl("file:///android_asset/index.html");
}

Android Manifest

uses-sdk android:minSdkVersion="16" android:targetSdkVersion="19"
uses-permission android:name="android.permission.INTERNET"

Server Side Code creating cookie:

Response.Cookies("mycookie")("myvalue") = "123456789"
Response.Cookies("mycookie").Expires = Date() + 10
Response.Cookies("mycookie").Secure = True

Server Side Code reading cookie:

Response.Write Request.Cookies("mycookie")("myvalue")
  • This returns a blank value on API 21 in WebView

When this runs on API 19 or below I can read/write cookies no problem. I am using cookies as you would with visiting any web page that uses cookies. Any help would be appreciated.


回答1:


API 21 or Lollipop requires this to be added to your APP

if (Build.VERSION.SDK_INT >= 21) {
    // AppRTC requires third party cookies to work
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptThirdPartyCookies(mWebView, true);
}

Works again!



来源:https://stackoverflow.com/questions/28418709/android-webview-http-cookies-not-working-in-api-21

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!