如何在没有异步的情况下使用 HttpClient

How to use HttpClient without async

你好,我正在关注 this guide

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 以及我怎样才能只得到响应字符串?

提前致谢

当然可以:

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 所说:

"That may cause deadlocks in ASP.NET and WinForms. Using .Result or .Wait() with TPL should be done with caution".

这里是 WebClient.DownloadString

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

is there any way to use HttpClient without async/await and how can I get only string of response?

HttpClient 专为异步使用而设计。

如果要同步下载字符串,使用WebClient.DownloadString