using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CPMeta { public class RestAPI { private static HttpClient RequestClient = new HttpClient(); private static HttpClient ResponseClient = new HttpClient(); public static int TimeOut { get; set; } = 3000; static RestAPI() { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; RequestClient.Timeout = TimeSpan.FromMilliseconds(TimeOut); } public static async Task PostAsync(string Url, REQUEST body) where REQUEST : class where RESPONSE : class { try { if (body != null) { Console.WriteLine($"PostAsync:{Url},{JsonConvert.SerializeObject(body, Formatting.Indented)}"); var jsonBody = JsonConvert.SerializeObject(body); var contents = new StringContent(jsonBody, Encoding.UTF8, "application/json"); //RequestClient.Timeout = TimeSpan.FromMilliseconds(TimeOut); var response = await RequestClient.PostAsync(Url, contents); var resContentStr = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(resContentStr); } } catch (Exception e) { Console.WriteLine($"TimeOut: {ResponseClient.Timeout}"); Console.WriteLine("PostAsync Error"); Console.WriteLine(e.Message); } return default(RESPONSE); } public static async Task GetAsync(string Url) { try { Console.WriteLine($"GetAsync:{Url}"); //ResponseClient.Timeout = TimeSpan.FromMilliseconds(TimeOut); var response = await ResponseClient.GetAsync(Url); var resContentStr = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(resContentStr); } catch(Exception e) { Console.WriteLine($"TimeOut: {ResponseClient.Timeout}"); Console.WriteLine("GetAsync Error"); Console.WriteLine(e.Message); } return default(RESPONSE); } } }