using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Windows.Forms; namespace MAutoUpdate.common { public static class UntilApi { private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } /// /// formform postData:请求内容例如:"key1=value1&key2=value2&key3=value3" /// /// /// /// public static string PostUrl(string url, string postData) { string result = ""; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.Timeout = 800;//请求超时时间 byte[] data = Encoding.UTF8.GetBytes(postData); req.ContentLength = data.Length; req.Timeout = 5000; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //获取响应内容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } catch (Exception e) { MessageBox.Show(e.ToString()); } return result; } //string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=北京"); //string ss = HttpGet("http://localhost:41558/eap/api/MacModel/Get?filter=WAC-026"); public static string HttpGet(string url) { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } #region http //string ss = HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}"); /// /// formbody json /// /// /// /// public static string HttpPost(string url, string body, int timeout = 50000) { try { Encoding encoding = Encoding.UTF8; HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } //(HttpWebRequest)WebRequest.Create(url); request.Timeout = timeout; request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/json"; byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } catch (Exception e) { LogTool.AddLog(e.ToString() + e.StackTrace); //MessageBox.Show(e.ToString()); return ""; } } /// /// 发送Get请求 /// /// 地址 /// 请求参数定义 /// public static string Get(string url, Dictionary dic) { string result = ""; StringBuilder builder = new StringBuilder(); builder.Append(url); if (dic.Count > 0) { builder.Append("?"); int i = 0; foreach (var item in dic) { if (i > 0) builder.Append("&"); builder.AppendFormat("{0}={1}", item.Key, item.Value); i++; } } try { //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); //ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072; //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString()); req.Method = "GET"; req.KeepAlive = false; req.Timeout = 5000; //req.Headers.Add("usercode", "S00001"); //添加参数 HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); using (Stream stream = resp.GetResponseStream()) { //获取内容 using (StreamReader reader = new StreamReader(stream)) { result = reader.ReadToEnd(); } } } catch (Exception ex) { LogTool.AddLog(ex.ToString() + ex.StackTrace); } finally { //stream.Close(); } return result; } #endregion #region https //public static string Get(string url, Dictionary dic) //{ // try // { // StringBuilder builder = new StringBuilder(); // builder.Append(url); // if (dic.Count > 0) // { // builder.Append("?"); // int i = 0; // foreach (var item in dic) // { // if (i > 0) // builder.Append("&"); // builder.AppendFormat("{0}={1}", item.Key, item.Value); // i++; // } // } // ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); // LogBLL.Err("api:" + builder.ToString()); // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(builder.ToString()); // //request.ProtocolVersion = HttpVersion.Version10; // //ServicePointManager.SecurityProtocol = (SecurityProtocolType)4080; // request.ProtocolVersion = HttpVersion.Version10; // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // request.Proxy = null; // request.KeepAlive = false; // request.Timeout = 5000; // request.Method = "GET"; // request.ContentType = "application/json; charset=UTF-8"; // request.AutomaticDecompression = DecompressionMethods.GZip; // HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Stream myResponseStream = response.GetResponseStream(); // StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); // string retString = myStreamReader.ReadToEnd(); // myStreamReader.Close(); // myResponseStream.Close(); // if (response != null) // { // response.Close(); // } // if (request != null) // { // request.Abort(); // } // return retString; // } // catch (Exception ex) // { // LogBLL.Err(ex.StackTrace); // return ""; // } //} ///// ///// post请求 string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}"); ///// ///// ///// ///// //public static string HttpPost(string url, string body, int timeout = 10000) //{ // try // { // LogBLL.Err("Postapi:" + url); // ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); // Encoding encoding = Encoding.UTF8; // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); // // request.ProtocolVersion = HttpVersion.Version10; // request.Method = "POST"; // request.Accept = "text/html, application/xhtml+xml, */*"; // request.ContentType = "application/json"; // byte[] buffer = encoding.GetBytes(body); // request.Timeout = timeout; // request.ContentLength = buffer.Length; // request.GetRequestStream().Write(buffer, 0, buffer.Length); // HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) // { // return reader.ReadToEnd(); // } // } // catch (Exception ex) // { // LogBLL.Err(ex.StackTrace); // return ""; // } //} #endregion #region //public static string PostHttpsRequest(string url, Dictionary parameters) //{ // ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); // var request = WebRequest.Create(url) as HttpWebRequest; // request.ProtocolVersion = HttpVersion.Version10; // request.CookieContainer = new CookieContainer(); // request.AllowAutoRedirect = true; // request.Timeout = 1000 * 60; // request.Method = "POST"; // request.ContentType = "application/x-www-form-urlencoded"; // request.Referer = url; // if (!(parameters == null || parameters.Count == 0)) // { // var param = ""; // foreach (var key in parameters.Keys) // { // param += "&" + key + "=" + parameters[key]; // } // using (var sw = new StreamWriter(request.GetRequestStream())) // { // sw.Write(param.Trim('&')); // sw.Close(); // } // } // var res = request.GetResponse() as HttpWebResponse; // var st = res.GetResponseStream(); // var sr = new StreamReader(st); // return sr.ReadToEnd(); //} #endregion } }