android - 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 来加载这个页面吗?
提前致谢
解决方案
这是因为您尝试访问的服务器不安全,即它使用的是 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>
推荐阅读
- python - 在 Python 3.x 中从另一个类调用类方法
- python - 单击提交按钮后,Django 表单应保持不变
- reactjs - 类型错误:更新时无法读取未定义反应 redux 的属性“地图”
- angular - 加载所有子内容时显示父组件角度4
- python - 在底图上使用倒钩绘制风时不显示
- python - 使用 Python 登录网站
- php - php 查询不使用 UTF-8 字符集
- php - WordPress有什么方法或任何片段来最小化标签'style amp-custom'中指定的样式表的渲染大小?
- git - 无法通过 GoDaddy 的 SMTP 服务器使用 Git 命令发送电子邮件
- java - 在 Android 中读取内部存储文件花费了太多时间