Call RESTful web services with this flexible GET format
using Newtonsoft.Json;
using System.Net.Http;
public static Response<T> Get<T> (string endpoint, Dictionary<string, string> parameters = null, bool throwExceptionOnFail = false, HTTPAuthentication authentication = null, bool parseResponse = true)
{
var response = new Response<T> { Success = true };
try
{
if (string.IsNullOrWhiteSpace(endpoint))
{
throw new Exception(string.Format(ResourceDomain.XCannotBeNullOrEmpty, "endpoint"));
}
var httpClient = new HttpClient();
var url = BuildURL(endpoint, parameters);
var request = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
if (authentication != null)
{
var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", authentication.User, authentication.Password));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
}
var httpResponse = httpClient.SendAsync(request).Result;
if (httpResponse.IsSuccessStatusCode)
{
if (parseResponse)
{
var res = httpResponse.Content.ReadAsStringAsync();
response.Value = JsonConvert.DeserializeObject<T>(res.Result);
}
}
else
{
throw new Exception(string.Format(ResourceDomain.HTTPError, httpResponse.StatusCode, httpResponse.ReasonPhrase));
}
}
catch(Exception ex)
{
response.Success = false;
response.Message = ex.Message;
if (throwExceptionOnFail)
{
throw ex;
}
}
return response;
}