Android网络请求报错(直接请求http)

62 阅读1分钟

直接请求https链接报错的原因是:Android 9.0 (API 28) 及更高版本默认禁止使用明文 HTTP 请求(只允许 HTTPS)。 比如通常配置域名的位置BASE_URLhttp://... 开头的,所以被系统拦截

这里有 三种解决方法,推荐尝试:

方法一:最快解决(全局允许 HTTP)

直接修改 AndroidManifest.xml 文件,在 <application> 标签中添加 android:usesCleartextTraffic="true"

位置: app/src/main/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.joygem.demo">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        
        <!-- 添加这一行 -->
        android:usesCleartextTraffic="true" 
        >
        
        <activity android:name=".MainActivity">
            <!-- ... -->
        </activity>
    </application>
</manifest>

添加完后,卸载 App 重新安装(有时直接运行配置不生效),再次尝试即可。


方法二:更规范的做法(配置网络安全文件)

如果只想允许特定的域名使用 HTTP,而不是全局允许,可以这样做(这在正式上架应用商店时更安全):

  1. res/xml 目录下新建一个文件 network_security_config.xml (如果 xml 目录不存在就创建它)。

  2. 填入以下内容:

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <!-- 允许该域名的 HTTP 请求 -->
        <domain-config cleartextTrafficPermitted="true">
            <domain includeSubdomains="true">test.xdf.cn</domain>
        </domain-config>
    </network-security-config>
    
  3. AndroidManifest.xml<application> 标签中引用这个配置:

    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
    

方法三:修改服务器地址(如果有 HTTPS)

如果测试服务器支持 HTTPS,最简单的办法是修改 NetworkApi 中的 BASE_URL

把: http://testmedia-vod-lan-roombox.test.xdf.cn 改为: https://testmedia-vod-lan-roombox.test.xdf.cn

(前提是服务端配置了 SSL 证书,否则会报证书握手错误)


建议

对于测试环境(Test Server),直接使用 方法一 是最省事的