本文介绍了如何在不异步的情况下使用HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我正在关注本指南
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;
}
我在我的代码上使用了这个示例,我想知道有什么方法可以使用 HttpClient
而无需 async/await
,如何仅获得响应字符串?
I use this example on my code and I want to know is there any way to use HttpClient
without async/await
and how can I get only string of response?
提前谢谢
推荐答案
您当然可以:
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所说:
but as @MarcinJuraszek said:
以下是 WebClient.DownloadString
using (var client = new WebClient())
{
string response = client.DownloadString(path);
if (!string.IsNullOrEmpty(response))
{
...
}
}
这篇关于如何在不异步的情况下使用HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!