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

问题描述:

我无法使用Xamarin表单中的PLC项目从webservice检索数据。 我已经尝试WebRequest和HttpClient,但得到各种例外。我也曾尝试 从这个样本运行代码:Xamarin Forms的问题从webservices/rest api检索json的问题

  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"); 
    

我也试着运行这个示例中的代码: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编写)并且它正在按照预期返回数据。

+0

您是使用iOS或Android进行测试的?如果是Android,您的应用是否启用了Internet权限? – Jason 2014-10-06 02:13:06

+0

是的,我在我的清单文件中有以下条目: noobie 2014-10-06 03:53:20

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

+0

当我的手机上安装api.geonames.org它的作品,所以可能是模拟器有关。将检查出这谢谢。 – noobie 2014-10-06 21:21:53

+0

愚蠢的错误!我在主机文件中创建了一个条目来间接映射本地主机地址。我现在正在得到命名解析错误,但正如您所提到的,可能与仿真器有关。 – noobie 2014-10-07 02:55:23