How to use HttpClient without async
is there any way to use HttpClient without async/await and how can I get only string of response?
HttpClient
was specifically designed for asynchronous use.
If you want to synchronously download a string, use WebClient.DownloadString
.
Of course you can:
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();
}
}
}
but as @MarcinJuraszek said:
"That may cause deadlocks in ASP.NET and WinForms. Using .Result or .Wait() with TPL should be done with caution".
Here is the example with WebClient.DownloadString
using (var client = new WebClient())
{
string response = client.DownloadString(path);
if (!string.IsNullOrEmpty(response))
{
...
}
}