首页 > 解决方案 > 连接到本地主机上的 API - Android 模拟器

问题描述

我尝试连接到在我的机器上本地运行的 API 以检索 Android 模拟器中的值。我不断收到 404 错误。知道这里应该为 API 做什么吗?谢谢您的帮助。

            var test = "";
            var url = "http://10.0.2.2:60002/api/values/" + Convert.ToInt32(Id);

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue(
                        "Basic", Convert.ToBase64String(
                            System.Text.ASCIIEncoding.ASCII.GetBytes(
                               $"{user}:{pass}")));
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                var response = await client.GetStringAsync(url);
                test = response;
            }
            return test;

标签: androidapiandroid-emulator

解决方案


使用 127.0.0.1 作为 IP 地址。它应该可以解决问题。
如果没有,请在命令提示符下键入“ adb shell ifconfig ”或“ adb shell ipaddr ”。
(其中一个应该可以工作)
检查您的任何一台机器的 IP 地址是否在那里。如果有匹配的,请使用它。
要检查您机器的 IP 地址,

  • 如果您使用的是 windows在命令提示符下
    键入ipconfig
  • 如果你使用 Linux在你的 shell 中输入ifconfig 。

推荐阅读