已配置usesCleartextTraffic WebView加载HTTP链接报ERR_CLEARTEXT_NOT_PERMITTED
配置问题排查及解决方案
核心错误点
- network_security_config的domain配置格式错误:
<domain>标签不允许携带http:///https://协议前缀,也不能写不规范的域名格式,你现有配置的两行domain均为错误写法:
修正后需移除协议前缀,同时删除域名开头多余的点:<!-- 错误写法 --> <domain includeSubdomains="true">https://xxxxxx.base.url</domain> <domain includeSubdomains="true">http://.xxxx.org</domain><!-- 正确写法 --> <domain includeSubdomains="true">xxxxxx.base.url</domain> <domain includeSubdomains="true">xxxx.org</domain>includeSubdomains="true"属性已经代表匹配该域名下所有子域名,不需要额外在域名前加前缀点。 - WebView未配置内部加载规则:仅开启JS权限无法保证链接在WebView内部打开,默认情况下点击WebView内的超链接会调用系统浏览器加载,不会应用你App的网络安全配置。需要在UIClass.kt中添加WebViewClient配置:
binding.webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { // 所有链接统一在当前WebView内加载 view?.loadUrl(request?.url.toString()) return true } }
可选优化点
- 你已经在
network_security_config.xml的<base-config>节点配置了全局明文流量许可,AndroidManifest.xml中的android:usesCleartextTraffic="true"属于重复配置,二者同时存在时系统会优先采用网络安全配置的规则,冗余配置可删除。 - 若仅需要放行特定域名的http请求,可以关闭
<base-config>的cleartextTrafficPermitted开关,仅在domain-config中配置需要放行的http域名,安全性更高。
内容的提问来源于stack exchange,提问作者Anshul Tyagi
相关产品推荐
相关产品推荐

