Using the HttpClient to Call REST web services from C# - 9/9/2013

I have found the new HTTP Client libraries a pleasure to work with. Here is my best practice outline of a typical chunk of client code for calling REST web services:

// Other usings...
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.HttpContentExtensions;

namespace ... // Give a useful namespace {

    public static class ____RestClient {

        // always provide one place to create the desired client
        private static HttpClient MakeClient() 
        {
            WebRequestHandler mainHandler = new WebRequestHandler();
            // Set up credentials (if any)
            mainHandler.Credentials = ...;
            HttpClient client = new System.Net.Http.HttpClient(mainHandler);
            // Set base address
            client.BaseAddress = new Uri(...); 
            // Say we want JSON back (or whatever you like)
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return client;
        }

        // Sample GET method (DELETE will be similar)
        public static _____Get({arguments}) {
            MyResultType results = null;
            using (HttpClient client = MakeClient())
            {
                HttpResponseMessage response = client.GetAsync("/{relative url}/" + {arguments}).Result;  
                if (response.IsSuccessStatusCode)
                {
                    // good result, process payload
                    results = response.Content.ReadAsAsync<{my datagram}>().Result;

                } 
                else 
                {
                    // something bad happended
                    MyLogger.Write("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                    var message = response.Content.ReadAsStringAsync().Result;
                    MyLogger.Write(message);
                    // You might want to throw an exception here
                }
            }                
            return results;
        }

        // Sample POST method (PUT will be similar)
        public static ____Post(MyArgumentsModel model) {
            MyResultType results = null;
            using (HttpClient client = MakeClient())
            {
                HttpResponseMessage response = client.PostAsJsonAsync("/{relative url}/", model).Result;
                if (response.IsSuccessStatusCode)
                {
                    // good result, process payload
                    results = response.Content.ReadAsAsync<MyResultType>().Result;
                } 
                else 
                {
                    // something bad happended
                    MyLogger.Write("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                    var message = response.Content.ReadAsStringAsync().Result;
                    MyLogger.Write(message);
                    // You might want to throw an exception here
                }
            }                
            return results;
        }

        // Others

    }
}

BTW: Nice code formatting provided by http://www.manoli.net/

Blog ID: 2013 09-09_Blog_1145