前言

  • android9.0坑:java.io.IOException: Cleartext HTTP traffic to android.bugly.qq.com not permitted

问题

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
java.io.IOException: Cleartext HTTP traffic to android.bugly.qq.com not permitted
        at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
        at com.tencent.bugly.proguard.ai.a(BUGLY:266)
        at com.tencent.bugly.proguard.ai.a(BUGLY:115)
        at com.tencent.bugly.proguard.al.run(BUGLY:355)
        at com.tencent.bugly.proguard.ak$2.run(BUGLY:757)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
        at java.util.concurrent.ThreadPoolExecutor.processTask(ThreadPoolExecutor.java:1187)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:784)

原因分析

  • Google针对 Android 系统(Android P) 的应用程序,将要求默认使用加密连接(TLS),目的是为了保证用户数据和设备的安全,因此在Android P系统中使用HttpUrlConnection进行http请求会出现上述问题。

解决办法

方法1:

  • 将app.gradle中将targetSdkVersion降到28以下

方法2:

  • 将http请求改为https请求,这种方案显然不太现实,一般项目的测试环境都是http请求。

方法3(推荐):

  • 修改AndroidManifest.xml文件

    • 1: 在res的xml文件中添加network_security_config.xml

    • 2:文件内容在network-security-config标签中配置如下:

    1
    2
    3
    4
    
    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config xmlns:android="http://schemas.android.com/apk/res/android">
        <base-config cleartextTrafficPermitted="true" />
    </network-security-config>
  • 3:在AndroidManifest.xml文件的applicaiton标签中配置networkSecurityConfig引用xml文件

总结