using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; namespace Infrastructure.Services { public class HttpClientService : IHttpClientService { public HttpClientService() { } public async Task GetAsync(HttpClient httpClient, string url, Dictionary queryParams = null, Dictionary headers = null) { try { var request = CreateGetRequest(url, queryParams, headers); var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsAsync(); } return default(T); } catch (Exception ex) { throw ex; } } public async Task GetStreamAsync(HttpClient httpClient, string url, Dictionary queryParams = null, Dictionary headers = null) { try { // TODO: Handle queryParams, headers return await httpClient.GetStreamAsync(url); } catch (Exception ex) { throw ex; } } public async Task PostAsJsonAsync(HttpClient httpClient, string url, object data, Dictionary queryParams = null, Dictionary headers = null) { try { var request = CreatePostAsJsonRequest(url, data, queryParams, headers); var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsAsync(); } return default(T); } catch (Exception ex) { throw ex; } } public async Task PostAsFormUrlEncodedAsync(HttpClient httpClient, string url, Dictionary data, Dictionary queryParams = null, Dictionary headers = null) { try { var request = CreatePostAsFormUrlEncodedRequest(url, data, queryParams, headers); var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsAsync(); } return default(T); } catch (Exception ex) { throw ex; } } #region Private Method private HttpRequestMessage CreatePostAsJsonRequest(string url, object data, Dictionary queryParams, Dictionary headers) { // TODO: Handle queryParams MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter(); HttpContent content = new ObjectContent(data, jsonFormatter); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = content, }; if (headers != null) { foreach (KeyValuePair entry in headers) { request.Headers.Add(entry.Key, entry.Value); } } return request; } private HttpRequestMessage CreatePostAsFormUrlEncodedRequest(string url, Dictionary data, Dictionary queryParams, Dictionary headers) { // TODO: Handle queryParams var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(data), }; if (headers != null) { foreach (KeyValuePair entry in headers) { request.Headers.Add(entry.Key, entry.Value); } } return request; } private HttpRequestMessage CreateGetRequest(string url, Dictionary queryParams, Dictionary headers) { // TODO: Handle queryParams var request = new HttpRequestMessage(HttpMethod.Get, url); foreach (KeyValuePair entry in headers) { request.Headers.Add(entry.Key, entry.Value); } return request; } #endregion } }