Using HttpClient for REST service calls

During a recent project we needed to make calls to a REST service out there on the net. I narrowed down the call to a basic method that I can call from other parts of my application.  This uses the HttpClient class and .Net 4.5

internal class RestHttpClient
{
    public async Task<HttpResponseMessage> SendRequestAsync(string uri, string xmlRequest)
    {
        using (HttpClient httpClient = new HttpClient())
        {
            StringContent httpContent = new StringContent(xmlRequest, Encoding.UTF8);
            HttpResponseMessage responseMessage;
            try
            {
                responseMessage = await httpClient.PostAsync(uri, httpContent);
            }
            catch (Exception ex)
            {
                responseMessage = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.InternalServerError,
                    ReasonPhrase = string.Format("RestHttpClient.SendRequestAsync failed: {0}", ex)
                };
            }
 
            return responseMessage;
        }
    }
}

Elsewhere in the application this method is called as follows:

public async Task SendRequest(string uri, string xmlRequest)
{
    RestHttpClient restHttpClient = new RestHttpClient();
    return await restHttpClient.SendRequestAsync(uri, xmlRequest);
}
Advertisements