我正在尝试调用web 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");
}
}
这里,代码在最后一行停止。我怎么能这样做?
答案 0 :(得分:1)
您可以使用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
}
Here是HttpStatusCode枚举的官方文档,它为您提供了可能的状态代码值的完整列表。
由于您的方法返回一个Task,您应该在调用它时等待它。
public async Task foo()
{
await RunAsync();
}