Android 11设备WebView中XMLHttpRequest请求失败(状态码0)求助
Android 11设备WebView中XMLHttpRequest返回状态码0的解决方案
针对你在Zebra TC52(Android 11)设备上WebView遇到的XMLHttpRequest返回状态码0、响应为空的问题,结合你的代码和环境,以下是具体排查和解决步骤:
1. 移除GET请求中不必要的Content-Type请求头
你的loadJSON函数中对GET请求设置了xhr.setRequestHeader('Content-Type', 'application/json');,但GET请求不需要发送Content-Type头,部分服务器会因不符合规范拒绝该请求,直接导致XHR返回状态码0。修改后的JavaScript代码:
function loadJSON(path, success) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { document.getElementById('table').style.visibility = "visible"; document.getElementById('status_value').textContent = xhr.status; document.getElementById('content_value').textContent = xhr.responseText; if (xhr.status === 200) { success(JSON.parse(xhr.responseText)); } } }; xhr.open('GET', path, true); // 移除不必要的Content-Type设置 xhr.send(); }
2. 正确配置WebView核心参数
Android WebView默认限制较多,需开启JavaScript、跨域资源访问等关键设置,确保能正常发起网络请求:
WebSettings webSettings = webView.getSettings(); // 启用JavaScript webSettings.setJavaScriptEnabled(true); // 启用DOM存储(部分API依赖) webSettings.setDomStorageEnabled(true); // 允许加载混合内容(若目标API涉及HTTPS和HTTP混合,Android 11需显式配置) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } // 允许文件访问 webSettings.setAllowFileAccess(true);
3. 配置Android网络安全规则
Android 11对网络请求有严格的安全限制,需确保应用允许访问目标API域名。在res/xml/network_security_config.xml中添加规则:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="false"> <!-- 允许访问目标API域名 --> <domain includeSubdomains="true">catfact.ninja</domain> </domain-config> </network-security-config>
然后在AndroidManifest.xml的application标签中引用该配置:
<application ... android:networkSecurityConfig="@xml/network_security_config">
4. 自定义WebViewClient排查错误
添加自定义WebViewClient,捕获请求过程中的错误信息,方便进一步排查:
webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); // 打印错误日志,定位问题 Log.e("WebViewXHR", "错误码: " + error.getErrorCode() + ", 描述: " + error.getDescription()); } });
以上步骤中,移除不必要的Content-Type头和正确配置WebView参数是解决状态码0问题的核心,多数情况下调整这两点即可恢复正常请求。
内容的提问来源于stack exchange,提问作者user20561885
相关产品推荐
相关产品推荐

