19

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

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
Kumar J.
  • 193
  • 1
  • 1
  • 5
  • you can refer this : http://stackoverflow.com/questions/31129873/make-http-client-synchronous-wait-for-response – Sunil Kumar Oct 24 '16 at 13:58
  • 3
    Why not `WebClient.DownloadString` instead of twisting `HttpClient` in ways it isn't meant to be used? – spender Oct 24 '16 at 14:02

2 Answers2

35

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.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
13

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))
    {
       ...
    }
}
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • 6
    Just FYI: That may cause deadlocks in ASP.NET and WinForms. Using `.Result` or `.Wait()` with TPL should be done with caution. – MarcinJuraszek Oct 23 '16 at 23:11
  • 2
    See this for info about deadlocking https://stackoverflow.com/questions/32195595/avoiding-deadlock-with-httpclient – Simon_Weaver Nov 16 '17 at 06:06