Guest User

Untitled

a guest
Jan 23rd, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. internal class ApiClient : HttpClient
  2. {
  3. private static readonly Lazy<ApiClient> lazyApiClient =
  4. new Lazy<ApiClient>(() => new ApiClient());
  5. private static readonly ApiClient instance = new ApiClient();
  6. static ApiClient() { }
  7. private ApiClient() : base()
  8. {
  9.  
  10. }
  11.  
  12. public static ApiClient Instance
  13. { get { return lazyApiClient.Value; } }
  14.  
  15. private async Task<T> SendAsyncRequest<T>(HttpRequestMessage httpRequestMessage) where T : IApiResponse
  16. {
  17. using (httpRequestMessage)
  18. {
  19. HttpResponseMessage response = await SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead)
  20. .ConfigureAwait(false);
  21. {
  22. response.EnsureSuccessStatusCode();
  23. string responeString = response.Content.ReadAsStringAsync().Result;
  24. return await response.Content.ReadAsAsync<T>();
  25. }
  26. }
  27. }
  28.  
  29. public async Task<T> Get<T>(string uriString) where T : IApiResponse
  30. {
  31. if (string.IsNullOrEmpty(uriString)) throw new Exception("missing request url");
  32. HttpRequestMessage httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(uriString) };
  33. return await SendAsyncRequest<T>(httpRequestMessage);
  34. }
  35.  
  36. public async Task<T> Post<T>(string jsonContent, string uriString) where T : IApiResponse
  37. {
  38. if (string.IsNullOrEmpty(jsonContent)) throw new ArgumentNullException("missing json content");
  39. if (string.IsNullOrEmpty(uriString)) throw new Exception("missing request url");
  40. StringContent stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
  41. HttpRequestMessage httpRequestMessage = new HttpRequestMessage { Content = stringContent, Method = HttpMethod.Post, RequestUri = new Uri(uriString) };
  42. return await SendAsyncRequest<T>(httpRequestMessage);
  43. }
  44. }
Add Comment
Please, Sign In to add comment