在使用OkHttp时遇到的坑

安卓9.0/P及以上版本因系统限制无法直接访问http,需要创建network_security_config.xml配置明文流量。AVD模拟器出现SocketException,通过在AndroidManifest.xml中设置网络配置并卸载重装应用解决。

安卓9.0/P及以上版本无法直接访问未加密http

我在本地配置的后端用的是http而不是https,结果无法访问,查阅资料后发现Android P 限制了明文流量的网络请求,非加密的流量请求都会被系统禁止掉。

解决方法:

参考自:Android 9.0/P okhttp网络请求出错
在res目录下新建一个xml目录,在xml目录下新建network_security_config.xml文件, 插入以下代码

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

之后在AndroidManifest.xml文件的appliction标签中加入:

android:networkSecurityConfig="@xml/network_security_config"

加入后如下:

<application
        android:networkSecurityConfig="@xml/network_security_config"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        >

AVD模拟器访问网络时报错 java.net.SocketException(socket failed: EPERM (Operation not permitted)),真机可以

使用Glide在获取网络图片时出错,之后在AndroidManifest.xml文件中加入

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>

并***卸载软件重装***后问题解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值