[英]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.