[英]C# Web API call
這是我第一次嘗試對API進行調用,但是我有點掙扎。 我一直在找回錯誤消息,我打算使用json響應來填充對象。 OMDB api說明在此處(盡管無濟於事): http ://www.omdbapi.com/
private static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://www.omdbapi.com/?");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("t=Captain+Phillips&r=json").Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Error with feed");
}
}
}
您將問號( ?
)放在錯誤的位置。 嘗試這樣:
private static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://www.omdbapi.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("?t=Captain+Phillips&r=json");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Error with feed");
}
}
}
注意,問號在這里:
HttpResponseMessage response = await client.GetAsync("?t=Captain+Phillips&r=json");
而不是放置在基本網址上。
同樣,為了正確地編寫異步方法,您需要在內部await
它,而不必急於調用.Result
屬性,這當然是一個阻塞操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.