namespace Collinson.Http.Security
{
public interface IJsonClientService
{
T Get<T>(string uri);
T Get<T>(string uri, object data);
T Post<T>(string uri);
T Post<T>(string uri, object data);
T Put<T>(string uri);
T Put<T>(string uri, object data);
}
}
using Newtonsoft.Json;
using System;using System.Net;
using System.Net.Http;
using System.Text;
namespace Collinson.Http.Security
{
public class JsonClientService : IJsonClientService
{
private readonly HttpClient client = null;
public JsonClientService(ClientSettings settings)
{
this.client = SigningHttpClientFactory.Create(settings.Username, settings.Password);
}
public T Get<T>(string uri)
{
HttpResponseMessage result = this.client.GetAsync(uri).Result;
this.ThrowIfUnauthorized(result);
string result2 = result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(result2);
}
public T Get<T>(string uri, object data)
{
string requestUri = string.Format("{0}?{1}", uri, HttpExtensions.ToQueryString(data));
HttpResponseMessage result = this.client.GetAsync(requestUri).Result;
this.ThrowIfUnauthorized(result);
string result2 = result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(result2);
}
public T Post<T>(string uri)
{
HttpResponseMessage result = this.client.PostAsync(uri, new StringContent(string.Empty)).Result;
this.ThrowIfUnauthorized(result);
string result2 = result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(result2);
}
public T Post<T>(string uri, object data)
{
string content = JsonConvert.SerializeObject(data);
HttpResponseMessage result = this.client.PostAsync(uri, new StringContent(content, Encoding.UTF8, "application/json")).Result;
this.ThrowIfUnauthorized(result);
string result2 = result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(result2);
}
public T Put<T>(string uri)
{
HttpResponseMessage result = this.client.PutAsync(uri, new StringContent(string.Empty)).Result;
this.ThrowIfUnauthorized(result);
string result2 = result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(result2);
}
public T Put<T>(string uri, object data)
{
string content = JsonConvert.SerializeObject(data);
HttpResponseMessage result = this.client.PutAsync(uri, new StringContent(content, Encoding.UTF8, "application/json")).Result;
this.ThrowIfUnauthorized(result);
string result2 = result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(result2);
}
private void ThrowIfUnauthorized(HttpResponseMessage response)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException("You are not allowed to access the resource");
}
}
}
}