我無法使用Xamarin表單中的PLC項目從webservice檢索數據。 我已經嘗試WebRequest和HttpClient,但得到各種例外。我也曾嘗試 從這個樣本運行代碼:Xamarin Forms的問題從webservices/rest api檢索json的問題
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);
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權限? – Jason 2014-10-06 02:13:06
是的,我在我的清單文件中有以下條目: –
noobie
2014-10-06 03:53:20