Google处于安全考虑,从 Android P开始,要求APP的请求都使用加密链接,也就是 https 来进行网络请求。
然而在实际的的运行过程中,网络资源的请求链接不一定是 https,http 的链接还是非常多的。特别是在使用别人网站的图片资源的时候,而且服务器资源是否采用 https 也往往由不得我们做 AndroidAPP开发的来决定,因此开始允许 http 请求还是非常必要的。
Android P 中进行 http 请求报错信息
2020-04-12 14:39:03.804 16413-16413/com.a404fan.video I/Glide: Root cause (1 of 1)
java.net.UnknownServiceException: CLEARTEXT communication to images.cnblogsc.com not permitted by network security policy
at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:176)
at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:233)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:107)
at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:75)
at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:245)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:82)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:74)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:502)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
报错为 UnknownServiceException ,未知服务器异常。
提示的信息为:
CLEARTEXT communication to images.cnblogsc.com not permitted by network security policy
意思是 网络安全策略不允许与images.cnblogsc.com进行明文通信,即为不允许进行 http 请求。
解决方法
既然默认不允许,那我们就手动地开启允许就好了。
首页在 res 资源目录中新建一个 xml 目录,然后再新建一个文件,任意起名,文件内容为:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
cleartextTrafficPermitted 意为允许明文传输,设置为 true 即可。
然后在 AndroidManifest.xml 的 application 中配置 networkSecurityConfig ,配置值就是刚刚新建的 xml 文件。
<application
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"
android:name=".App"
android:networkSecurityConfig="@xml/network_security_config"
tools:ignore="GoogleAppIndexingWarning">
</application>
因为我的 xml 文件命名为 network_security_config.xml 所以这里配置的是 @xml/network_security_config 。
再次运行APP,就已经可以正常进行 http 请求了。
Comments | NOTHING