以下两种方法getData1Async()
和getData2Async()
基本相同吗?如果是这样,为什么我不需要EnsureSuccessStatusCode()
方法中的getData2Async()
?
class Program
{
static void Main(string[] args)
{
try
{
string uri = "https://www.blahblah.com/getdata";
Task<string> x = getData1Async(uri);
System.Diagnostics.Debug.WriteLine(x.Result);
Task<string> y = getData2Async(uri);
System.Diagnostics.Debug.WriteLine(y.Result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static async Task<string> getData1Async(string uri)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(uri);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
static async Task<string> getData2Async(string uri)
{
var httpClient = new HttpClient();
return await httpClient.GetStringAsync(uri);
}
}
答案 0 :(得分:1)
getData1Async - 这里你得到HttpResponseMessage类型的对象,如果你不确保响应已成功完成并调用response.Content.Read ...,答案将是不确定的。 getData2Async - 直接调用httpClient本身来获取字符串,该字符串在内部确保它仅在收到数据时返回。