异常:CLEARTEXT communication ** not permitted by network security policy - 简书
使用okhttp时遇到异常java.net.UnknownServiceException: CLEARTEXT communication ** not permitted by network security policy
原因
在Android P(API 28)系统的设备上,默认要求使用加密连接。譬如,默认只能使用HTTPS进行通信,若强行使用HTTP通信,则会得到上面的异常。
解决办法
- 创建
res/xml/network_security_config.xml
文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
2.在AndroidManifest.xml
下的application标签增加networkSecurityConfig属性:
<application
android:networkSecurityConfig="@xml/network_security_config"
>
<!-- -->
</application>
[点击并拖拽以移动]
或者
在AndroidManifest.xml文件中,添加属性:
android:usesCleartextTraffic="true"
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.StOkhhtp"
android:usesCleartextTraffic="true"
tools:targetApi="31">