Android9.0 http请求异常

一:Okhttp网络请求时候报异常: java.net.UnknownServiceException: CLEARTEXT communication to ** not permitted by network security policy
原因是当targetSdkVersion>=28时,OkHttp通过调用Android API中的isCleartextTrafficPermitted(host),在9.0系统上限制了Http明文请求。
方式一:把targetSdkVersion改成小于28版本
方式二:把请求接口改为https
方式三:通过配置Xml文件绕过Http限制
1.在res文件下创建一个xml文件,可以命名network_config:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>

<base-config cleartextTrafficPermitted="true" />

</network-security-config>
2.然后在AndroidMainfest.xml文件下的
<application
android:networkSecurityConfig="@xml/network_config">
</application>
二:Volley网络请求时候报异常:Cleartext HTTP traffic to * not permitted
方式一:把targetSdkVersion改成小于28版本
方式二:把请求接口改为https
方式三:1.在AndroidMainfest.xml文件下application节点下
<application
android:usesCleartextTraffic="true">
</application>
2.如果添加了上述代码程序还是无法运行,并出现闪退或报错“Didn’t find class “org.apache.http.ProtocolVersion” on path”的情况,在application节点
<application>
<uses-library
android:name="org.apache.http.legacy" android:required="false" />
</application>


Rocky_ruan
57 声望5 粉丝

不积跬步,无以至千里