Hello I'm following to 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;
}
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?
Thank you in advance
All methods with HttpClient are asynchronous. HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL. It is a supported async feature of .NET framework. HttpClient is able to process multiple concurrent requests. It is a layer over HttpWebRequest and HttpWebResponse.
Are You Using HttpClient in The Right Way? When an ASP NET application needs to talk to an external service or API, it needs to make an HTTP Request. When using ASP.NET to build an application, HTTP requests is made using an instance of the HttpClient class. An HttpClient class acts as a session to send HTTP Requests.
IsSuccessStatusCode) { Console.WriteLine("Success"); } HttpClient only supports DeleteAsync method because Delete method does not have a request body. HttpClient is used to send an HTTP request, using a URL.
In this code, PostAsJsonAsync method serializes the object into JSON format and sends this JSON object in POST request. HttpClient has a built-in method "PostAsXmlAsync" to send XML in POST request. Also, we can use "PostAsync" for any other formatter.
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))
{
...
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With