首页 > 解决方案 > android WebView 无法加载受 Cloudflare 保护的网页

问题描述

我正在开发一个安卓应用程序。我的应用程序中有一个 webview,它将加载一个网页。

    webView = findViewById(R.id.web_view);
    webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 SECSSOBrowserChrome");
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("xxxx.html");

我用 测试过https://www.google.com,webView 工作正常。但加载 xxx.html 失败(此站点受 Cloudflare 保护)

我像这样添加了 WebViewClient

webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                    KLog.d(TAG, "onPageStarted " + url);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                    KLog.d(TAG, "host =" + request.getUrl().toString());
                    view.loadUrl(request.getUrl().toString());
                    return true;
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    KLog.d(TAG, "onPageFinished " + url);
                }

                @Override
                public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                    super.onReceivedError(view, request, error);
                    KLog.d(TAG,"onReceivedError " + error.getDescription() + "Error code = " + error.getErrorCode());
                }
            });

但是 public void onPageStarted(WebView view, String url, Bitmap favicon) { 从不调用。

等了好久才得到这张图

https://drive.google.com/file/d/12DmOGWNqKcq5IsMiQEApmtnvequOIxqD/view?usp=drivesdk

你能帮我用 android WebView 来加载这个页面吗?

提前致谢

标签: androidandroid-webviewcloudflare

解决方案


这是因为您尝试访问的服务器不安全,即它使用的是 HTTP(不是 HTTPS)。

Android P 默认使用 HTTPS。这意味着如果您在应用程序中使用未加密的 HTTP 请求,该应用程序将在除 Android P 之外的所有 Android 版本中正常运行。

为避免这种安全性,请尝试在您的应用代码中进行以下更改。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application android:networkSecurityConfig="@xml/network_security_config"
                    ... >
        ...
    </application>
</manifest>

并在 res/xml 添加文件名为:network_security_config.xml

network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        //  Add host of your URL in below line. 
        //   ie. if url is  "https://www.google.com/search?source=...."
        //   then just add "www.google.com"
        <domain includeSubdomains="true">www.myanmartvchannel.com</domain>
    </domain-config>
</network-security-config>

推荐阅读