【问题标题】:Issues with Xamarin Forms retrieving json from webservices / rest apiXamarin Forms 从 webservices/rest api 检索 json 的问题
【发布时间】:2014-10-06 02:05:28
【问题描述】:

我在使用 Xamarin 表单中的 PLC 项目从 Web 服务检索数据时遇到问题。 我已经尝试了 WebRequest 和 HttpClient 但得到了各种异常。我也试过 运行此示例中的代码:

  1. 连接失败(网络无法访问)

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create ("http://localhost:3000/profile/contacts");
            webRequest.UseDefaultCredentials = true;
            webRequest.Method = "GET";
            webRequest.Accept = "application/json";
            webRequest.ContentType = "application/json";
            webRequest.BeginGetResponse ((ar) => {
                var request = (HttpWebRequest)ar.AsyncState;
                try {
                    using (var response = (HttpWebResponse)request.EndGetResponse (ar)) {                              
                        var s = response.GetResponseStream ();
                    }
                } catch (Exception ex) {
                    var xy = ex;
                }
    
            }, webRequest);
    
  2. ConnectFailure(请求的地址在此上下文中无效)

                var client = new System.Net.Http.HttpClient ();
                client.BaseAddress = new Uri("http://localhost:3000/");
                client.DefaultRequestHeaders.Clear ();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.GetStringAsync ("profile/contacts");
    

我还尝试运行此示例中的代码:https://github.com/conceptdev/xamarin-forms-samples/tree/master/HttpClient/HttpClientDemo 尝试发出请求时会引发 namesresolutionfail 异常。

var client = new System.Net.Http.HttpClient ();
                client.BaseAddress = new Uri("http://api.geonames.org/");
                var response = await client.GetAsync("earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt");
                var earthquakesJson = response.Content.ReadAsStringAsync().Result;
                var rootobject = JsonConvert.DeserializeObject<Rootobject>(earthquakesJson);
                return rootobject.earthquakes;

我已经测试了我的 rest api(用 Node.Js 编写),它正在按预期返回数据。

【问题讨论】:

  • 您是使用 iOS 还是 Android 进行测试?如果是 Android,您的应用是否启用了 Internet 权限?
  • 是的,我的清单文件中有以下条目:

标签: rest xamarin httpclient webrequest


【解决方案1】:

Eee,什么是 Android 的 localhost?它不知道 localhost 实际上是您的计算机。根据 api.geonames.org,这可能是一个模拟器问题。你在哪里测试你的应用程序?试试真机。

【讨论】:

  • 在我的手机上安装 api.geonames.org 时它可以工作,所以可能与模拟器有关。会检查一下谢谢。
  • 愚蠢的错误!我在主机文件中创建了一个条目来间接映射本地主机地址。我现在收到命名解析错误,但正如你提到的,可能与模拟器有关。
猜你喜欢
  • 2019-11-18
  • 1970-01-01
  • 1970-01-01
  • 2019-02-21
  • 2016-08-10
  • 2021-02-20
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多