Http请求不能在主线程使用
界面不能在子线程中更新
安卓9不能使用http
今天用OKHttp访问自己云服务器上的资源,结果总是出错,还以为是我代码写错了。去查询了错误信息java.net.UnknownServiceException: CLEARTEXT communication to *** not permitted by network security policy
,才发现,安卓9居然不能用http而只能用https请求。
根据别人的博客,有两种解决方法
-
把 targetSdkVersion 降到27以下
-
在
res/xml
中定义一个xml文件,写入以下内容:<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
并在
AndroidManifest.xml
的application
标签下增加android:networkSecurityConfig="@xml/上面那个文件的基本名"