1 public static class ClientHelper 2 { 3 public static string HttpPost(string url, string content) 4 { 5 string result = string.Empty; 6 try 7 { 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 }
标签:帮助,return,string,url,request,buffer,HttpPost From: https://www.cnblogs.com/bingshao/p/16775518.html