Ketchup Ketchup - 1 year ago 116
ASP.NET (C#) Question

Why use HttpClient for Synchronous Connection

I am building a class library to interact with an API. I need to call the API and process the XML response. I can see the benefits of using HttpClient for Asynchronous connectivity, but what I am doing is purely synchronous, so cannot see any significant benefit over HttWebRequests.

If anyone can shed any light I would greatly appreciate it. I am not one for using new technology for the sake of it.

Answer Source

but what i am doing is purely synchronous

You could use HttpClient for synchronous requests just fine:

using (var client = new HttpClient())
    var response = client.GetAsync("").Result;

    if (response.IsSuccessStatusCode)
        // by calling .Result you are performing a synchronous call
        var responseContent = response.Content; 

        // by calling .Result you are synchronously reading the result
        string responseString = responseContent.ReadAsStringAsync().Result;


As far as why you should use HttpClient over WebRequest is concerned, well, HttpClient is the new kid on the block and could contain improvements over the old client.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download