我正在制作 Xamarin.Forms 应用程序,它应该从 api 获取 JSON,然后允许显示它。到目前为止我的代码:
public async void jsonDownload()
{
connect();
await downloadData();
}
public void connect()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async Task<List<Jsonclass>> downloadData()
{
String url = "https://my-json-server.typicode.com/kgbzoma/TestJsonFile/all";
var uri = new Uri(string.Format(url, string.Empty));
try
{
var response = await client.GetAsync(uri).ConfigureAwait(false);
response.EnsureSuccessStatusCode(); //NEVER GET HERE
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
List = JsonConvert.DeserializeObject<List<Jsonclass>>(content);
}catch (Exception ex)
{
Debug.WriteLine(@" Error {0}", ex.Message);
}
return List;
}
Run Code Online (Sandbox Code Playgroud)
问题是代码甚至不去 response.EnsureSuccessStatusCode(); 所以我的对象列表是空的。在 UWP 版本上,它可以正常工作。这里我刚开始出现异常:System.Net.Http.HttpRequestException 带有消息发送请求时发生错误。