诗情寻知己
揽几缕、轻挽起,暮暮朝朝与君语。
 1     public static class ClientHelper
 2     {
 3         public static string HttpPost(string url, string content)
 4         {
 5             string result = string.Empty;
 6             try
 7             {
           //在.net core 中不需要if及if内的内容,会影响请求,导致无法访问
8 //if (url.StartsWith("https")) 9 //{ 10 //ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; 11 //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; 12 //} 13 Encoding encoding = Encoding.UTF8; 14 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 15 request.Method = "POST"; 16 request.Accept = "text/html, application/xhtml+xml, */*"; 17 if (!string.IsNullOrEmpty(content)) 18 { 19 request.ContentType = "application/json"; 20 byte[] buffer = encoding.GetBytes(content); 21 request.ContentLength = buffer.Length; 22 request.GetRequestStream().Write(buffer, 0, buffer.Length); 23 } 24 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 25 using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) 26 { 27 result = reader.ReadToEnd(); 28 } 29 } 30 catch (Exception ex) 31 { 32 LogHelper.Error(string.Format("[HttpPost出错]-[{0}]", url), ex); 33 } 34 return result; 35 } 36 public static T Post<T>(string url, string json) where T : class 37 { 38 var str = HttpPost(url, json); 39 if (!string.IsNullOrWhiteSpace(str)) 40 { 41 return JsonConvert.DeserializeObject<T>(str); 42 } 43 else 44 { 45 return null; 46 } 47 } 48 } 49 }

 

posted on 2022-10-10 14:05  诗情寻知己  阅读(45)  评论(0)    收藏  举报