简体   繁体   中英

C# Web API call

This is the first time i've tried making a call to an API and I'm struggling a little. I keep getting back my error message, I plan on using the json response to populate my object. The OMDB api instructions are here (not helpful though): 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");
        }
    }
}

You have placed the question mark ( ? ) on the wrong place. Try like this:

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

Notice that the question mark is here:

HttpResponseMessage response = await client.GetAsync("?t=Captain+Phillips&r=json");

and not on the base url as you placed it.

Also in order to properly write your asynchronous method you need to await on it inside and not be eagerly calling the .Result property which of course is a blocking operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM