Xamarin Forms的问题从webservices / rest api检索json

时间:2014-10-06 02:05:29

标签: rest xamarin httpclient webrequest

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

  1. ConnectFailure(网络无法访问)

    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");
    
  3. 我还尝试运行此示例中的代码: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;
    

    我已经测试了我的其余api(用Node.Js编写)并且它按预期返回数据。

1 个答案:

答案 0 :(得分:2)

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