【问题标题】:Android app failing to connect local hostAndroid 应用无法连接本地主机
【发布时间】:2021-11-03 16:21:10
【问题描述】:

尝试连接本地服务器 5000 上的本地 Api 并失败

通过浏览器连接到 http://127.0.0.1:5000/user/1 工作正常。

连接到外部 api 也可以正常工作。

尝试使用 android retrofit 连接到相同的地址, 不断获得 跳过 xxx 帧!应用程序可能在其主线程上做了太多工作。

清单文件。

<?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"></uses-permission>
    <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>

解决的问题

  1. 网址 = 10.0.2.2
  2. 添加android:usesCleartextTraffic="true" 显示应用程序标签。

【问题讨论】:

  • 我可以看看你的代码吗?你也可以发布你的清单应用程序标签吗?
  • 你在用模拟器吗?
  • 是的,使用模拟器。

标签: android localhost retrofit


【解决方案1】:

Android Emulator 是一个模拟的独立设备。因此,像 127.0.0.1 这样的本地主机地址将解析为 Android 模拟器的本地主机,而不是您正在运行它的计算机。

你应该改用地址

10.0.2.2

https://developer.android.com/studio/run/emulator-networking

【讨论】:

  • 已经检查过了,但不工作。不确定它是否相关,我尝试连接到本地服务器以检索数据,然后才在应用程序上使用数据。
  • 那么是连接失败还是获取数据失败......这些是非常不同的事情。
  • 我知道。但问题仍然存在,与本地 api 的连接失败。
  • 按照建议使用 10.0.2.2 解决问题并将android:usesCleartextTraffic="true" 添加到清单应用程序标记。
猜你喜欢
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2021-05-07
  • 2013-07-14
  • 2019-04-08
相关资源
最近更新 更多