Android中app发送Http请求出现W/System.err: java.io.IOException: Cleartext HTTP traffic to xxx

╄→гoц情女王★ 提交于 2020-01-26 19:59:48

原因

在新版Android 9.0 (API 28)中,规定所有应用程序默认使用 Https进行网络通信,不能使用Http进行明文通信。这个规定会导致app的Http访问权限受限,进而会抛出异常
W/System.err: java.io.IOException: Cleartext HTTP traffic to www.xxx.com

解决办法

  1. 改用Https访问,前提是服务器支持Https且有SSL证书,否则会抛出异常 javax.net.ssl.SSLHandshakeException: Handshake failed

  2. targetSdkVersion降到27(含)以下

  3. 自定义网络安全设置①
    在 AndroidManifest.xml 的 application 标签中设置 networkSecurityConfig 属性:

    <application
        ...
        android:allowBackup="true"
        android:icon="${app_icon}"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
    </application>
    

    然后在 res 目录下新建 xml 文件夹,创建 xml 文件 network_security_config.xml 如下:

    <?xml version="1.0" encoding="utf-8"?>
    			<network-security-config>
    			<base-config cleartextTrafficPermitted="true"/>
    			</network-security-config>
    

    或将xml中的内容替换成如下:

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
    	<base-config cleartextTrafficPermitted="true">
        	<trust-anchors>
            		<certificates src="system" />
        	</trust-anchors>
    	</base-config>
    </network-security-config>
    
  4. 自定义网络安全设置②
    在AndroidManifest.xml配置文件的<application>标签中直接插入使用明文通信 android:usesCleartextTraffic="true"

     <application
         ...
         android:allowBackup="true"
         android:icon="${app_icon}"
         android:label="@string/app_name"
         android:usesCleartextTraffic="true"
         ...>
     </application>
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!