如何在不使用async的情况下使用HttpClient

21

你好,我正在按照这个指南操作。

static async Task<Product> GetProductAsync(string path)
{
    Product product = null;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        product = await response.Content.ReadAsAsync<Product>();
    }
    return product;
}

我在我的代码中使用这个例子,想知道是否有不用async/await的方法来使用HttpClient,并且如何获取响应字符串?

提前致谢。


将HTTP客户端变为同步,等待响应。 - Sunil Kumar
3
为什么不使用 WebClient.DownloadString,而要把 HttpClient 扭曲成不应该使用的方式? - spender
2个回答

35
有没有办法在不使用async/await的情况下使用HttpClient,并且如何只获取响应的字符串?
HttpClient是专门为异步使用而设计的。
如果您想同步下载字符串,请使用WebClient.DownloadString。
编辑:从.net 5开始,HttpClient有一个同步的API。

3
哈哈!我刚刚留下了一条评论,表示同意这个观点是正确答案。 - spender
谢谢,但我只是按照我在问题中指定的指南进行操作。 - Kumar J.
4
遵循指南的一部分就是知道需要做哪些更改。 - Stephen Cleary
这应该被标记为正确答案。我自己也遇到了这个问题。 - Westley Bennett
3
有趣的是,最近我才了解到(在此回答之后5年),HttpClient在.NET 5中具有同步API - Stephen Cleary

14
当然可以:
public static string Method(string path)
{
   using (var client = new HttpClient())
   {
       var response = client.GetAsync(path).GetAwaiter().GetResult();
       if (response.IsSuccessStatusCode)
       {
            var responseContent = response.Content;
            return responseContent.ReadAsStringAsync().GetAwaiter().GetResult();
        }
    }
 }

但正如@MarcinJuraszek所说:

"这可能会导致ASP.NET和WinForms中的死锁。在使用TPL时,使用.Result或.Wait()应谨慎处理"。

以下是使用WebClient.DownloadString的示例:

using (var client = new WebClient())
{
    string response = client.DownloadString(path);
    if (!string.IsNullOrEmpty(response))
    {
       ...
    }
}

6
只是提供信息:这可能会在ASP.NET和WinForms中导致死锁。使用TPL的.Result.Wait()应该谨慎进行。 - MarcinJuraszek
2
请参阅此处有关死锁的信息:https://dev59.com/-47ea4cB1Zd3GeqPA2zV - Simon_Weaver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接