Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- internal class ApiClient : HttpClient
- {
- private static readonly Lazy<ApiClient> lazyApiClient =
- new Lazy<ApiClient>(() => new ApiClient());
- private static readonly ApiClient instance = new ApiClient();
- static ApiClient() { }
- private ApiClient() : base()
- {
- }
- public static ApiClient Instance
- { get { return lazyApiClient.Value; } }
- private async Task<T> SendAsyncRequest<T>(HttpRequestMessage httpRequestMessage) where T : IApiResponse
- {
- using (httpRequestMessage)
- {
- HttpResponseMessage response = await SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead)
- .ConfigureAwait(false);
- {
- response.EnsureSuccessStatusCode();
- string responeString = response.Content.ReadAsStringAsync().Result;
- return await response.Content.ReadAsAsync<T>();
- }
- }
- }
- public async Task<T> Get<T>(string uriString) where T : IApiResponse
- {
- if (string.IsNullOrEmpty(uriString)) throw new Exception("missing request url");
- HttpRequestMessage httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(uriString) };
- return await SendAsyncRequest<T>(httpRequestMessage);
- }
- public async Task<T> Post<T>(string jsonContent, string uriString) where T : IApiResponse
- {
- if (string.IsNullOrEmpty(jsonContent)) throw new ArgumentNullException("missing json content");
- if (string.IsNullOrEmpty(uriString)) throw new Exception("missing request url");
- StringContent stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
- HttpRequestMessage httpRequestMessage = new HttpRequestMessage { Content = stringContent, Method = HttpMethod.Post, RequestUri = new Uri(uriString) };
- return await SendAsyncRequest<T>(httpRequestMessage);
- }
- }
Add Comment
Please, Sign In to add comment