Skip to main content
 首页 » 编程设计

C# 网络 API 调用

2024年02月06日14rubylouvre

这是我第一次尝试调用 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"); 

而不是在你放置它的基础 url 上。

此外,为了正确编写您的异步方法,您需要在其内部 await 而不是急切地调用 .Result 属性,这当然是一个阻塞操作。