C# HTTP或HTTPS Get请求 和 Post 请求
一、GET请求 C# HTTP或HTTPS GET请求URL 获得返回信息
private string GetUrl(string url) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true; request.ProtocolVersion = HttpVersion.Version11; // 这里设置了协议类型。 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; request.KeepAlive = false; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.Expect100Continue = false; } request.Method = "GET"; //使用get方式发送数据 request.ContentType = "application/x-www-form-urlencoded"; request.Referer = null; request.AllowAutoRedirect = true; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; request.Accept = "*/*"; //获取网页响应结果 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); string result = string.Empty; using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } return result; }
GarsonZhang www.yesdotnet.com
二、POST请求 C# HTTP或HTTPS POST请求URL 获得返回信息
JSON格式
private static string PostUrl(string url, string postData) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true; request.ProtocolVersion = HttpVersion.Version11; // 这里设置了协议类型。 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; request.KeepAlive = false; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.Expect100Continue = false; } request.Method = "POST"; //使用get方式发送数据 request.ContentType = "application/x-www-form-urlencoded"; request.Referer = null; request.AllowAutoRedirect = true; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; request.Accept = "*/*"; byte[] data = Encoding.UTF8.GetBytes(postData); Stream newStream = request.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); //获取网页响应结果 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); string result = string.Empty; using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } return result; }
GarsonZhang www.yesdotnet.com
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员