React Native使用axios时Android7及以下设备API调用失败如何解决
Android 7及更低版本axios请求抛出Network Error解决方案
问题原因
- Android 7及更低版本系统默认未全局启用TLS 1.2及更高版本的HTTPS协议支持,当前绝大多数线上HTTPS服务都已停用TLS 1.0、TLS 1.1等安全性较低的旧协议,导致旧设备无法完成SSL握手,直接触发网络错误。
- 若服务端使用的CA证书不在Android 7及更低版本的系统信任根证书列表中,也会导致证书校验失败,触发同类报错。
可行解决方案
方案1:原生端强制启用TLS 1.2(生产环境推荐)
修改安卓原生项目配置开启旧版本系统的TLS 1.2支持:
- 在
android/app/build.gradle文件中添加依赖:
dependencies { // 其他原有依赖保留,新增以下两项 implementation 'com.google.android.gms:play-services-safetynet:18.0.1' implementation 'com.squareup.okhttp3:okhttp:3.14.9' }
- 在MainActivity的
onCreate生命周期方法中添加初始化代码:
import android.os.Build; import com.google.android.gms.security.ProviderInstaller; import javax.net.ssl.SSLContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 仅对Android 7及更低版本做兼容处理 if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) { try { ProviderInstaller.installIfNeeded(getApplicationContext()); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); sslContext.createSSLEngine(); } catch (Exception e) { e.printStackTrace(); } } }
方案2:axios临时关闭证书校验(仅测试用,禁止生产环境使用)
测试阶段临时验证问题时,可以修改axios配置关闭证书校验,风险极高生产环境严禁使用:
import axios from 'axios'; import https from 'https'; const SERVER_URL = 'https://*****.com/****'; // 创建自定义axios实例 const customAxios = axios.create({ baseURL: SERVER_URL, httpsAgent: new https.Agent({ // 关闭证书校验,仅测试时开启 rejectUnauthorized: false }) }); export const getCities = () => async dispatch => { // 替换原有axios.get为自定义实例的请求方法 let res = await customAxios.get(`/GetCityList`); res = parser.parse(res.data).ArrayOfMCity.mCity; if (res && !res.length) { res = [res]; } const dropdownCities = []; res.forEach(r => { dropdownCities.push({label: r.CityName, value: r.CityID}); }); dispatch({ type: GET_CITY, payload: { cities: res ? res : [], dropdownCities, }, }); };
方案3:服务端做兼容处理
无需修改客户端代码,联系服务端运维人员做两项配置调整即可:
- 在HTTPS服务配置中开启对TLS 1.1版本协议的支持
- 更换服务端SSL证书为Android 7及更低版本系统信任的根CA机构签发的证书
内容的提问来源于stack exchange,提问作者hassanqshi
相关产品推荐
相关产品推荐

