gpt4 book ai didi

c# - 为什么要使用 HttpClient 进行同步连接

转载 作者:IT王子 更新时间:2023-10-29 03:30:41 26 4
gpt4 key购买 nike

我正在构建一个类库来与 API 交互。我需要调用 API 并处理 XML 响应。我可以看到使用 HttpClient 进行异步连接的好处,但我所做的是纯同步的,所以我看不出使用 HttpWebRequest 有什么明显的好处。

如果有人能提供任何帮助,我将不胜感激。我不是那种为了新技术而使用新技术的人。

最佳答案

but what i am doing is purely synchronous

您可以使用 HttpClient 进行同步请求:

using (var client = new HttpClient())
{
var response = client.GetAsync("http://google.com").Result;

if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;

// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result;

Console.WriteLine(responseString);
}
}

就为什么要使用 HttpClient 而不是 WebRequest 而言,好吧,HttpClient 是新手,可以包含对旧客户端的改进。

关于c# - 为什么要使用 HttpClient 进行同步连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14435520/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com