Android应用使用Retrofit无法连接本地localhost 5000端口服务怎么办?
问题描述
尝试连接本地服务器5000端口的API时失败。通过浏览器访问http://127.0.0.1:5000/user/1可正常访问,连接外部API也无异常。但在Android应用中使用Retrofit访问同一地址时,持续报错:Skipped xxx frames! The application may be doing too much work on its main thread.。
已配置的manifest文件内容如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android_movieapp"> <uses-permission android:name="android.permission.INTERNET" /> <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/Theme.AndroidmovieApp"> <activity android:name=".MovieListActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
解决方案
- 将请求URL的IP替换为
10.0.2.2。安卓模拟器默认将宿主机的本地地址映射为10.0.2.2,直接使用127.0.0.1会访问模拟器本身的端口,无法连通宿主机上运行的服务。 - 在manifest文件的application标签中添加
android:usesCleartextTraffic="true"配置。安卓9及以上系统默认禁止明文HTTP请求,未添加该配置时会拦截本地未加密的HTTP请求导致访问失败。
内容的提问来源于stack exchange,提问作者Shl
相关产品推荐
相关产品推荐

