C#Web API调用

时间:2015-01-25 13:39:26

标签: c# json api

这是我第一次尝试拨打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");
        }
    }
}

1 个答案:

答案 0 :(得分:4)

您已将问号(?)放在错误的位置。试试这样:

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属性,这当然是一个阻塞操作。