using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Net; using System.Text; using WCS.Core.Log; using static System.Net.WebRequest; namespace WCS.WebApi { public class APICaller { private class Result { public bool Succsess; public string Exception; public object Data; } private static ConcurrentDictionary Results = new ConcurrentDictionary(); public static T CallApi2(string url, object parameter, string type = "POST") { var content = JsonConvert.SerializeObject(parameter); var result = HttpApi(url, content, type); return JsonConvert.DeserializeObject(result); } public static T CallApi(string url, object parameter, string type = "Post") { var content = JsonConvert.SerializeObject(parameter); //var key = url + content; // if (Results.ContainsKey(key)) //{ // var res = Results[key]; // if (res == null) // throw new WarnException("接口调用中"); // try // { // if (!res.Succsess) // throw new WarnException(res.Exception); // return (T)res.Data; // } // finally // { // Results.Remove(key, out res); // } //} //else //{ // Results[key] = null; // var task = Task.Run(() => // { var res = new Result(); try { var result = HttpApi(url, content, type); res.Data = JsonConvert.DeserializeObject(result); //res.Succsess = true; } catch (Exception ex) { res.Exception = ex.Message; } return (T)res.Data; //finally //{ // Results[key] = res; //} // }); //task.Wait(50); //if (task.IsCompleted) //{ // return CallApi(url, parameter, type); //} //else //{ // throw new WarnException("接口调用中"); //} } private static string HttpApi(string url, string jsonstr, string type) { var sw = new Stopwatch(); sw.Start(); var encoding = Encoding.UTF8; #pragma warning disable SYSLIB0014 var request = (HttpWebRequest)Create(url);//webrequest请求api地址 #pragma warning restore SYSLIB0014 request.Timeout = 60000;//连接超时 request.ReadWriteTimeout = 3600000;//读写超时 request.Accept = "text/html,application/xhtml+xml,*/*"; request.ContentType = "application/json"; request.Method = type.ToUpper().ToString();//get或者post var buffer = encoding.GetBytes(jsonstr); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); var response = (HttpWebResponse)request.GetResponse(); using var reader = new StreamReader(response.GetResponseStream()!, Encoding.UTF8); var res = reader.ReadToEnd(); sw.Stop(); if (sw.ElapsedMilliseconds > 500) InfoLog.INFO_TIMING($"接口{url}调用耗时{sw.ElapsedMilliseconds}---------{JsonConvert.SerializeObject(res)}"); return res; } } }