using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace ICSSoft.FromERP { public class HttpHelper { #region Get请求 ///// ///// 发送http Get请求 ///// ///// ///// //public static string GetRequest(string url) //{ // HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; // request.Method = "GET"; // request.ContentType = "application/x-www-form-urlencoded";//链接类型 // string result = GetResponseString(request.GetResponse() as HttpWebResponse); // return result; //} /// /// 从HttpWebResponse对象中提取响应的数据转换为字符串 /// /// /// public static string GetResponseString(HttpWebResponse webresponse) { using (Stream s = webresponse.GetResponseStream()) { StreamReader reader = new StreamReader(s, Encoding.UTF8); return reader.ReadToEnd(); } } #endregion public static bool PingTest(string ip) { System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingReply pingStatus = ping.Send(IPAddress.Parse(ip), 1000); if (pingStatus.Status == System.Net.NetworkInformation.IPStatus.Success) { return true; } else { return false; } } public static bool WebRequestTest(string url) { try { System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url); System.Net.WebResponse myResponse = myRequest.GetResponse(); } catch (System.Net.WebException) { return false; } return true; } /// /// POST请求 /// /// 地址 /// 请求json /// token /// public static async Task HttpClientPost(string url, string requestJson, string contentType = "application/json", string token = "") where T : new() { string result = string.Empty; Uri postUrl = new Uri(url); using (HttpContent httpContent = new StringContent(requestJson, System.Text.Encoding.UTF8, contentType)) { //使用注入的httpclientfactory获取client using (var httpClient = new HttpClient()) { //设置请求头 //设置超时时间 if (!string.IsNullOrEmpty(token)) httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); httpClient.Timeout = new TimeSpan(0, 0, 60); var response = httpClient.PostAsync(url, httpContent).Result; result = response.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject(result); } } } public static async Task HttpClientGet(string url) where T : new() { using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage res = httpClient.GetAsync(url).Result; var t = res.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject(t); }; } } }