简体   繁体   中英

Android WebView HTTP Cookies not working in API 21

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM