Search code examples
c#asp.netdotnet-httpclient

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 I cannot see any significant benefit over using HttpWebRequest.

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


Solution

  • For anyone coming across this now, .NET 5.0 has added a synchronous Send method to HttpClient. https://github.com/dotnet/runtime/pull/34948

    The merits as to why where discussed at length here: https://github.com/dotnet/runtime/issues/32125

    You can therefore use this instead of SendAsync. For example

    public string GetValue()
    {
        var client = new HttpClient();
                
        var webRequest = new HttpRequestMessage(HttpMethod.Post, "http://your-api.com")
        {
            Content = new StringContent("{ 'some': 'value' }", Encoding.UTF8, "application/json")
        };
    
        var response = client.Send(webRequest);
    
        using var reader = new StreamReader(response.Content.ReadAsStream());
                
        return reader.ReadToEnd();
    }
    

    This code is just a simplified example - it's not production ready.