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;

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

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


Popular Posts

How To Mock Out Child Components In Unit Tests of Angular 2 Code

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

A Red Herring When Using Moq to Mock Methods With Optional Parameters

Mocking an IQueryable Return Value‏