繁体   English   中英

调用Web API

[英]Calling web API

我正在尝试调用网络api,我想查看得到的响应。 是200、204还是500。

我正在第一次尝试。

public void foo()
{
  RunAsync(); // dont know what it return type will be
}


static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:9000/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync("pid=23&lang=en-us");

            }
        }

在这里,代码在最后一行停止。 我怎样才能做到这一点 ?

您可以使用HttpResponseMessage的StatusCode属性。

HttpResponseMessage response = await client.GetAsync("pid=23&lang=en-us");
if (response.IsSuccessStatusCode)
{
    //was success
    var result = await response.Content.ReadAsStringAsync();     
    //checck result string now
   //you can also deserialize the response to your custom type if needed.
}
else
{
  var statusCode = response.StatusCode;
  //do something with this
}

是HttpStatusCode枚举的官方文档,该文档为您提供了可能的状态代码值的完整列表。

由于您的方法返回一个Task,因此您应在调用它时等待它。

public async Task foo()
{    
   await RunAsync(); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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