【问题标题】:I can not connect my Android device to a local database with REST API我无法使用 REST API 将我的 Android 设备连接到本地数据库
【发布时间】:2018-04-05 19:06:47
【问题描述】:

我的需求:将我的 Android 设备连接到本地 SQL Server 数据库。
我的问题:尝试连接时发生异常(“发送请求时发生错误”)
我使用的是:Visual Studio 2017 和具有 MVVM 架构的 Xamarin Forms。 什么有效:我从 Postman 发送了一个 POST,它运行良好,返回了用户的令牌。
我的项目使用 REST API 连接到数据库。 API 发布为 FileSystem 并使用 IISExpress 运行,正如我所说,它可以使用 Postman。
我试过了:
http://localhost:50965
http://192.168.1.106:50965(我的电脑IP)

我在 API Web.config 上的连接字符串

<add name="DefaultConnection" connectionString="Data Source=192.168.1.106; Initial Catalog=Gesuro; Integrated Security=True; User ID = sergio; Password=xxxxxxxx" providerName="System.Data.SqlClient" />

我对 API 的调用:

        var token = await this.apiService.GetToken(
            "http://localhost:50965",
            this.Email, 
            this.Password);  

我的 API 方法:

    public async Task<TokenResponse> GetToken(
        string urlBase,
        string username,
        string password)
    {
        try
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri(urlBase);
            var response = await client.PostAsync("Token",
                new StringContent(string.Format(
                "grant_type=password&username={0}&password={1}",
                username, password),
                Encoding.UTF8, "application/x-www-form-urlencoded"));
            var resultJSON = await response.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<TokenResponse>(
                resultJSON);
            return result;
        }
        catch (Exception e)
        {
            var pepe = e.Message;
            return null;
        }
    }

我已经在 Google 上搜索了三天并尝试了不同的解决方案……但没有结果。
我希望我的查询是具体的。请帮忙?
提前致谢。

【问题讨论】:

  • 我不确定 Xamarin 是否存在与普通 Android 相同的问题,即:要通过物理设备连接到 localhost,您的设备和 PC 必须连接到同一个互联网(最好是 Wi-Fi),但您可以尝试将localhost 更改为 ip:10.0.2.2 并尝试运行模拟器,因为 Xamarin 有这样的东西。
  • 数据库是什么设备本地的?
  • 您也可以尝试使用ngrok工具,在短时间内模拟真实服务器。它会为您生成随机 URL,然后您只需将 localhost 替换为生成的任何 URL ngrok,然后调用 API 试试运气。
  • 不要使用本地主机。使用 IP 或 FQDN。并确保 IIS 设置为允许远程连接。
  • 正如我在帖子中所写的,除了 localhost 之外,我已经尝试连接到我的 IP PC。数据库是 PC 本地的。我也试过模拟器。当我回到家时,我会尝试您向我提出的解决方案。

标签: android rest xamarin httpclient postman


【解决方案1】:

尝试更改compile using Android version (Target Framework) 更改它 android 6.0 可能会工作

我遇到了同样的问题,更改目标框架为我解决了这个问题。

【讨论】:

    【解决方案2】:

    你没有提供足够的细节,但我猜。 您的数据库服务器正在您的 PC 上运行,然后运行

    $ adb reverse tcp:50965 tcp:50965
    

    就可以了,然后当你访问

    localhost:50965
    

    在您的设备上,它将被重定向到您 PC 上的同一端口

    编辑

    如果您想测试 reverse 是否有效,请执行

    $ adb reverse tcp:3456 tcp:80
    

    如果您在设备上打开 Chrome 并进入

    ,您正在 PC 上的端口 80 上运行 Web 服务器
    http://127.0.0.1:3456
    

    你会看到主页

    【讨论】:

    • 谢谢,迭戈,但这也不起作用。 adb 工作正常,但我收到同样的错误。
    猜你喜欢
    • 2014-02-05
    • 1970-01-01
    • 2012-04-13
    • 2015-03-05
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多