【问题标题】:Cannot connect to a local network server in Visual Studio Xamarin Android无法连接到 Visual Studio Xamarin Android 中的本地网络服务器
【发布时间】:2023-03-18 01:51:01
【问题描述】:

我在 Visual Studio 社区中使用 Xamarin; 我正在尝试连接到远程数据库但没有成功。

尝试过 WCF、REST、HttpRequest - 没有一个可以连接到远程服务器/服务。 但是,在“新控制台应用程序”中,一切正常。 还做了“新的Android项目”,它也无法连接到服务/服务器。

以下代码在控制台应用程序中有效,但无法在 Xamarin Mono (Visual Studio) 中连接:

HttpWebRequest request = HttpWebRequest.Create(string.Format(@"http://192.168.16.100/RestService/RestServiceImpl.svc/json/12"));
request.ContentType = "application/json";
request.Method = "GET";

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    if (response.StatusCode != HttpStatusCode.OK)
    {
        Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
    }

    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        var content = reader.ReadToEnd();
        if (string.IsNullOrWhiteSpace(content))
        {
            Console.Out.WriteLine("Response contained empty body...");
        }
        else
        {
            Console.Out.WriteLine("Response Body: \r\n {0}", content);
        }
    }
}
Console.ReadLine();

【问题讨论】:

  • 是 IIS 上的本地服务吗?
  • 是的是本地的,但无论如何我尝试使用来自互联网的链接并且在控制台应用程序中工作但在 Xamarin 中不起作用;这个链接只是一个互联网链接: var request = HttpWebRequest.Create(string.Format(@"rxnav.nlm.nih.gov/REST/RxTerms/rxcui{0}/allinfo", "198440"));在 Xamarin 中不起作用;我不明白为什么?我必须支付一些认证?还是什么??
  • 主机http://192.168.16.100/是什么?
  • 从我的角度来看,Visual Studio Xamarin Android 无法连接到远程服务? ...为什么在我的新控制台应用程序中工作?在 Xamarin Android 中它不起作用?
  • 可以的。您可以通过 Android Emulator 连接到在线服务,但不能直接连接到本地服务。如果你想在 Android Emulator 中连接到localhost127.0.0.1,你必须写10.0.2.2。但在你的情况下,我不知道如何连接到http://192.168.16.100/

标签: c# visual-studio android-emulator xamarin.android


【解决方案1】:

你试过Windows Communication Foundation (WCF)吗?

对我来说,它作为自托管 wcf 服务非常有用。 (确保以管理员身份运行 selfhoster,否则会失败)

您需要下载:SlSvcUtil 以创建您的应用客户端并将其包含在您的 xamarin 项目中。

【讨论】:

  • 谢谢;我的 Android 手机的互联网连接是否关闭;我打开了WIFI并且能够连接;但现在我的手机上有互联网,但它不再工作了......我认为需要为我的手机设置一些权限才能连接......如何设置我的 Android 应用程序连接到的权限互联网?
  • 将以下内容添加到您的 AndroisManifest.xml 文件中: 如果您想检查 Wifi 是否可用或 networkstate b4 您连接到服务,您必须再添加 2 个权限。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 2015-10-29
  • 2016-05-14
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多