React Native Android端Axios网络错误问题求助
Android端HTTP请求失败(域名失效/IP正常)的排查方案
这种情况几乎可以确定是Android端的DNS解析异常——毕竟直接用IP能正常请求,说明请求逻辑、服务器配置都没问题,问题出在域名到IP的转换环节。以下是具体的解决步骤:
清除DNS缓存
物理设备:进入WiFi/移动网络设置,忘记当前网络后重新连接,能强制刷新DNS缓存。
模拟器:直接重启模拟器,或者执行adb shell ip -s flush dns(Android 10+有效)。配置自定义DNS服务器
在Android项目中指定可靠的公共DNS,避免系统默认DNS解析失败。- 在
android/app/src/main/res/xml/目录下创建network_security_config.xml:<network-security-config> <domain-config> <domain includeSubdomains="true">你的目标域名</domain> <dns> <server>8.8.8.8</server> <!-- Google DNS --> <server>1.1.1.1</server> <!-- Cloudflare DNS --> </dns> </domain-config> </network-security-config> - 在
AndroidManifest.xml的<application>标签中添加引用:android:networkSecurityConfig="@xml/network_security_config"
- 在
确认网络权限配置
检查AndroidManifest.xml是否包含必要权限,没加的话补上:<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />验证域名DNS记录有效性
用终端执行nslookup 你的域名,查看返回的IP是否和你手动测试的一致。如果域名刚更新过DNS记录,Android端可能存在缓存延迟,需要等待一段时间或者强制刷新。手动解析域名发起请求
如果以上方法都无效,可以在代码层手动解析域名后再请求(以fetch为例):// 借助react-native-dns-polyfill库解析域名 import dns from 'react-native-dns-polyfill'; async function fetchWithCustomDns() { try { const ips = await dns.resolve('你的域名'); const targetIp = ips[0]; // 发起请求时必须携带Host头,否则服务器无法识别域名 const response = await fetch(`http://${targetIp}/你的接口路径`, { headers: { 'Host': '你的域名', 'Content-Type': 'application/json' } }); const data = await response.json(); return data; } catch (error) { console.error('请求失败:', error); } }
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

