【问题标题】:Using WebClient to connect to Web Service使用 WebClient 连接到 Web Service
【发布时间】:2014-08-08 04:38:12
【问题描述】:

我编写了一个使用 JSON 的 C# Web Api 2 Web 服务应用程序。我现在想将此 Web 服务中的数据检索到我的 Xamarin 应用程序中。

这是我的 Xamarin 代码:

public AndroidMapCompanyViewModel GetMapCompanyFromWebService(string URL)
{
    AndroidMapCompanyViewModel androidMapCompanyViewModel = new AndroidMapCompanyViewModel ();
    using (var webClient = new System.Net.WebClient()) 
    {

        var json = webClient.DownloadString(URL);
        androidMapCompanyViewModel = JsonConvert.DeserializeObject<AndroidMapCompanyViewModel>(json);
    }
    return androidMapCompanyViewModel;
}

我收到以下错误:

Error: ConnectFailure (Network is unreachable)

使用以下网址:

"http://localhost:22101/api/MapCompanyAPI/1"

单击错误的详细信息时,列表顶部显示以下内容:

System.ArgumentException: Illegal characters in path.

如果我打开浏览器,我可以成功连接到 URL。

能否请我帮忙从我的 localhost url 反序列化 json 数据?

提前致谢

【问题讨论】:

  • 您是否为您的应用正确设置了权限?您能否尝试将您的 URL 转换为 Uri 对象并将其输出到控制台以查看是否存在无法正确转换的字符问题?
  • 如果我将准确的 json 数据放入一个文本文件并将其放置在我的 http Web 服务器上,我的应用程序将毫无错误地检索数据。该错误必须与仅使用我的本地主机有关。
  • 只是检查,但您在运行此 Xamarin 代码的同一智能手机上运行此 WebService?
  • 我在 VS2013 中运行 Web 服务,在默认本地主机上。
  • 哦,这就是为什么...手机看不到我的本地主机可以吗。

标签: json url xamarin webclient asp.net-web-api2


【解决方案1】:

显然您使用 localhost 来指代您的桌面计算机。以下是您将 Android 设备连接到桌面本地主机的方法。

android connect to PC's localhost when debugger on mobile device

此外,使用 HttpClient 而不是 WebClient 可能会更好。这是一个使用我刚刚拼凑起来的 HttpClient 的示例。

public void DownloadJson ()
{
    using (var httpClient = new HttpClient ())
    {
        var response = httpClient.GetAsync (URL).Result;

        if (response.IsSuccessStatusCode) {
            var responseContent = response.Content;
            string contents = responseContent.ReadAsStringAsync ().Result;

            // insert your code here
        }
    }
}

【讨论】:

猜你喜欢
  • 2015-12-24
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 2018-11-22
  • 2013-05-16
  • 1970-01-01
相关资源
最近更新 更多