A Generic Method Using HttpClient to Make a Synchronous Get Request

A while back I wrote a post on how to make an HTTP Get request using the HttpWebRequest object in .NET, implemented in a Generic method. Last week I had two occasions during which to revisit this code, but using the HttpClient class introduced in .NET 4.5 instead. The code below is functionally similar to the code in my earlier post, but uses HttpClient instead of HttpWebRequest.

A few points of interest:

  • The HttpClient.GetAsync() method returns a Task that is executed asynchronously (hence the name), however, calling the Result property of that Task ensures that the asynchronous operation is complete before returning. By accessing it off of the GetAsync() return value as shown below, we are essentially blocking and changing the call into a synchronous one.
  • The EnsureSuccessStatusCode() method of the HttpResponseMessage class will throw an exception of the response does not indicate success.

        public T ExecuteGet(string url)
        {
            if (String.IsNullOrWhiteSpace(url))
                throw new ArgumentException("url is required.");

            using (var client = new HttpClient())
            {
                HttpResponseMessage response = client.GetAsync(url).Result;
                   
                response.EnsureSuccessStatusCode();

                if (response.Content == null)
                    return default(T);

                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                var obj = serializer.ReadObject(response.Content.ReadAsStreamAsync().Result);
                return (T)obj;
            }
        }

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader