public class HttpClientHelper { private static MediaTypeWithQualityHeaderValue JsonMediaType = new MediaTypeWithQualityHeaderValue("application/json"); public static async Task GetAsync(string url) { using (var httpClient = new HttpClient()) { var uri = new Uri(url); var resp = await httpClient.GetAsync(uri); await resp.Content.ReadAsStringAsync(); } } public static async Task<T> GetAsync<T>(string url) { using (var httpClient = new HttpClient()) { var uri = new Uri(url); var resp = await httpClient.GetAsync(uri); var jsonResult = await resp.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(jsonResult); } } public static async Task PostAsync(string url, object parameters) { StringContent content = null; if (parameters != null) { var json = JsonConvert.SerializeObject(parameters); content = new StringContent(json, Encoding.UTF8); content.Headers.ContentType = JsonMediaType; } using (var httpClient = new HttpClient()) { var uri = new Uri(url); var resp = await httpClient.PostAsync(uri, content); await resp.Content.ReadAsStringAsync(); } } public static async Task<T> PostAsync<T>(string url, object parameters) { StringContent content = null; if (parameters != null) { var json = JsonConvert.SerializeObject(parameters); content = new StringContent(json, Encoding.UTF8); content.Headers.ContentType = JsonMediaType; } using (var httpClient = new HttpClient()) { var uri = new Uri(url); var resp = await httpClient.PostAsync(uri, content); var jsonResult = await resp.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(jsonResult); } } }
HttpGet:
using (var httpClient = new HttpClient()) { var responseStr = httpClient.GetAsync(requestUri).Result.Content.ReadAsStringAsync().Result; return Json(responseStr); }
HttpPost:
var requestString = JsonConvert.SerializeObject(dto); using (var httpClient = new HttpClient()) { using (var httpContent = new StringContent(requestString, Encoding.UTF8, "application/json")) { string requestUri = ""; var postTask = httpClient.PostAsync(requestUri, httpContent); postTask.Wait(System.Threading.Timeout.Infinite); var readTask = postTask.Result.Content.ReadAsStringAsync(); readTask.Wait(System.Threading.Timeout.Infinite); var result = readTask.Result; return Json(result); } }