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

这个报错的原因是:Android 9.0 (API 28) 及更高版本默认禁止使用明文 HTTP 请求(只允许 HTTPS)。

根据之前的代码, BASE_URLhttp://... 开头的,所以被系统拦截了。

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

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

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

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

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 复制代码
    <?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> 标签中引用这个配置:

    xml 复制代码
    <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),直接使用 方法一 是最省事的。

相关推荐
g105655913940 分钟前
LAMP博客平台Wordpress实战
android·mysql·nginx·php
hunterandroid2 小时前
[Android 从零到一] Compose LazyColumn 性能优化:key、稳定性与重组治理
android·前端
pengyu2 小时前
【Kotlin 协程修仙录 · 元婴境 · 中阶】 | 操作符真解:Flow 中间操作符与数据流变幻术
android·kotlin
pengyu3 小时前
【Kotlin 协程修仙录 · 元婴境 · 初阶】 | 冷流初啼:Flow 的基础与响应式编程的入门
android·kotlin
wawo003 小时前
Kuikly实践-从Android compose迁移到kuikly compose
android
Carson带你学Android5 小时前
Android 版 MCP 正式登场:AppFunctions
android·ai编程·jetbrains
古法安卓8 小时前
Android-Direct Boot 阶段与 getFilesDir() 路径变更问题深度分析
android·java·android studio
阿巴斯甜8 小时前
Android Studio Detekt 使用
android
杉氧9 小时前
Flutter 跨平台多端适配与 Android/iOS 一键自动化打包发布
android·前端·flutter
Super 含9 小时前
Android 包体积优化(一):APK 到底大在哪里?从 APK 结构到体积分析
android·ide·vscode