在WebView中设置Cookie

时间:2019-07-05 08:22:50

标签: java android cookies webview webkit

我正在尝试在WebView中设置一个cookie。我尝试了很多在Internet上找到的方法,但没有一个起作用。我有cookie字符串;我使用SharedPreferences从另一个班级获得了Cookie。

下面是我的代码:

string cookie = prefs.getString("Cookie", "");
string mypdfurl = "//pdf url";

android.webkit.CookieManager cookieManager = CookieManager.getInstance();
String[] splitCookies = cookie.split(";");
for (String cookie : splitCookies) {
    String[] cookieParts = cookie.split("=");
    if (cookieParts.length > 0) {
        String newCookie = cookieParts[0].trim();
        cookieManager.setCookie(myPdfUrl, newCookie);
    }
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    android.webkit.CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
}

Map<String, String> header = new HashMap<String, String>();
header.put("Cookie", cookie);
webView.loadUrl(myPdfUrl, header);

webView.setVisibility(View.VISIBLE);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.setWebViewClient(new WebViewClient());

webView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url="+myPdfUrl);

0 个答案:

没有答案