UntilApi.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Security;
  7. using System.Security.Cryptography.X509Certificates;
  8. using System.Text;
  9. using System.Windows.Forms;
  10. namespace MAutoUpdate.common
  11. {
  12. public static class UntilApi
  13. {
  14. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  15. {
  16. return true;
  17. }
  18. /// <summary>
  19. /// formform postData:请求内容例如:"key1=value1&key2=value2&key3=value3"
  20. /// </summary>
  21. /// <param name="url"></param>
  22. /// <param name="postData"></param>
  23. /// <returns></returns>
  24. public static string PostUrl(string url, string postData)
  25. {
  26. string result = "";
  27. try
  28. {
  29. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  30. req.Method = "POST";
  31. req.ContentType = "application/x-www-form-urlencoded";
  32. req.Timeout = 800;//请求超时时间
  33. byte[] data = Encoding.UTF8.GetBytes(postData);
  34. req.ContentLength = data.Length;
  35. req.Timeout = 5000;
  36. using (Stream reqStream = req.GetRequestStream())
  37. {
  38. reqStream.Write(data, 0, data.Length);
  39. reqStream.Close();
  40. }
  41. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  42. Stream stream = resp.GetResponseStream();
  43. //获取响应内容
  44. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  45. {
  46. result = reader.ReadToEnd();
  47. }
  48. }
  49. catch (Exception e)
  50. {
  51. MessageBox.Show(e.ToString());
  52. }
  53. return result;
  54. }
  55. //string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=北京");
  56. //string ss = HttpGet("http://localhost:41558/eap/api/MacModel/Get?filter=WAC-026");
  57. public static string HttpGet(string url)
  58. {
  59. Encoding encoding = Encoding.UTF8;
  60. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  61. request.Method = "GET";
  62. request.Accept = "text/html, application/xhtml+xml, */*";
  63. request.ContentType = "application/json";
  64. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  65. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  66. {
  67. return reader.ReadToEnd();
  68. }
  69. }
  70. #region http
  71. //string ss = HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}");
  72. /// <summary>
  73. /// formbody json
  74. /// </summary>
  75. /// <param name="url"></param>
  76. /// <param name="body"></param>
  77. /// <returns></returns>
  78. public static string HttpPost(string url, string body, int timeout = 50000)
  79. {
  80. try
  81. {
  82. Encoding encoding = Encoding.UTF8;
  83. HttpWebRequest request = null;
  84. //如果是发送HTTPS请求
  85. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  86. {
  87. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  88. request = WebRequest.Create(url) as HttpWebRequest;
  89. request.ProtocolVersion = HttpVersion.Version10;
  90. }
  91. else
  92. {
  93. request = WebRequest.Create(url) as HttpWebRequest;
  94. }
  95. //(HttpWebRequest)WebRequest.Create(url);
  96. request.Timeout = timeout;
  97. request.Method = "POST";
  98. request.Accept = "text/html, application/xhtml+xml, */*";
  99. request.ContentType = "application/json";
  100. byte[] buffer = encoding.GetBytes(body);
  101. request.ContentLength = buffer.Length;
  102. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  103. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  104. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  105. {
  106. return reader.ReadToEnd();
  107. }
  108. }
  109. catch (Exception e)
  110. {
  111. LogTool.AddLog(e.ToString() + e.StackTrace);
  112. //MessageBox.Show(e.ToString());
  113. return "";
  114. }
  115. }
  116. /// <summary>
  117. /// 发送Get请求
  118. /// </summary>
  119. /// <param name="url">地址</param>
  120. /// <param name="dic">请求参数定义</param>
  121. /// <returns></returns>
  122. public static string Get(string url, Dictionary<string, string> dic)
  123. {
  124. string result = "";
  125. StringBuilder builder = new StringBuilder();
  126. builder.Append(url);
  127. if (dic.Count > 0)
  128. {
  129. builder.Append("?");
  130. int i = 0;
  131. foreach (var item in dic)
  132. {
  133. if (i > 0)
  134. builder.Append("&");
  135. builder.AppendFormat("{0}={1}", item.Key, item.Value);
  136. i++;
  137. }
  138. }
  139. try
  140. {
  141. //如果是发送HTTPS请求
  142. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  143. {
  144. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  145. //ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
  146. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
  147. }
  148. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
  149. req.Method = "GET";
  150. req.KeepAlive = false;
  151. req.Timeout = 5000;
  152. //req.Headers.Add("usercode", "S00001");
  153. //添加参数
  154. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  155. using (Stream stream = resp.GetResponseStream())
  156. {
  157. //获取内容
  158. using (StreamReader reader = new StreamReader(stream))
  159. {
  160. result = reader.ReadToEnd();
  161. }
  162. }
  163. }
  164. catch (Exception ex)
  165. {
  166. LogTool.AddLog(ex.ToString() + ex.StackTrace);
  167. }
  168. finally
  169. {
  170. //stream.Close();
  171. }
  172. return result;
  173. }
  174. #endregion
  175. #region https
  176. //public static string Get(string url, Dictionary<string, string> dic)
  177. //{
  178. // try
  179. // {
  180. // StringBuilder builder = new StringBuilder();
  181. // builder.Append(url);
  182. // if (dic.Count > 0)
  183. // {
  184. // builder.Append("?");
  185. // int i = 0;
  186. // foreach (var item in dic)
  187. // {
  188. // if (i > 0)
  189. // builder.Append("&");
  190. // builder.AppendFormat("{0}={1}", item.Key, item.Value);
  191. // i++;
  192. // }
  193. // }
  194. // ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  195. // LogBLL.Err("api:" + builder.ToString());
  196. // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(builder.ToString());
  197. // //request.ProtocolVersion = HttpVersion.Version10;
  198. // //ServicePointManager.SecurityProtocol = (SecurityProtocolType)4080;
  199. // request.ProtocolVersion = HttpVersion.Version10;
  200. // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
  201. // request.Proxy = null;
  202. // request.KeepAlive = false;
  203. // request.Timeout = 5000;
  204. // request.Method = "GET";
  205. // request.ContentType = "application/json; charset=UTF-8";
  206. // request.AutomaticDecompression = DecompressionMethods.GZip;
  207. // HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  208. // Stream myResponseStream = response.GetResponseStream();
  209. // StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
  210. // string retString = myStreamReader.ReadToEnd();
  211. // myStreamReader.Close();
  212. // myResponseStream.Close();
  213. // if (response != null)
  214. // {
  215. // response.Close();
  216. // }
  217. // if (request != null)
  218. // {
  219. // request.Abort();
  220. // }
  221. // return retString;
  222. // }
  223. // catch (Exception ex)
  224. // {
  225. // LogBLL.Err(ex.StackTrace);
  226. // return "";
  227. // }
  228. //}
  229. ///// <summary>
  230. ///// post请求 string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}");
  231. ///// </summary>
  232. ///// <param name="url"></param>
  233. ///// <param name="body"></param>
  234. ///// <returns></returns>
  235. //public static string HttpPost(string url, string body, int timeout = 10000)
  236. //{
  237. // try
  238. // {
  239. // LogBLL.Err("Postapi:" + url);
  240. // ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  241. // Encoding encoding = Encoding.UTF8;
  242. // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  243. // // request.ProtocolVersion = HttpVersion.Version10;
  244. // request.Method = "POST";
  245. // request.Accept = "text/html, application/xhtml+xml, */*";
  246. // request.ContentType = "application/json";
  247. // byte[] buffer = encoding.GetBytes(body);
  248. // request.Timeout = timeout;
  249. // request.ContentLength = buffer.Length;
  250. // request.GetRequestStream().Write(buffer, 0, buffer.Length);
  251. // HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  252. // using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  253. // {
  254. // return reader.ReadToEnd();
  255. // }
  256. // }
  257. // catch (Exception ex)
  258. // {
  259. // LogBLL.Err(ex.StackTrace);
  260. // return "";
  261. // }
  262. //}
  263. #endregion
  264. #region
  265. //public static string PostHttpsRequest(string url, Dictionary<string, string> parameters)
  266. //{
  267. // ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  268. // var request = WebRequest.Create(url) as HttpWebRequest;
  269. // request.ProtocolVersion = HttpVersion.Version10;
  270. // request.CookieContainer = new CookieContainer();
  271. // request.AllowAutoRedirect = true;
  272. // request.Timeout = 1000 * 60;
  273. // request.Method = "POST";
  274. // request.ContentType = "application/x-www-form-urlencoded";
  275. // request.Referer = url;
  276. // if (!(parameters == null || parameters.Count == 0))
  277. // {
  278. // var param = "";
  279. // foreach (var key in parameters.Keys)
  280. // {
  281. // param += "&" + key + "=" + parameters[key];
  282. // }
  283. // using (var sw = new StreamWriter(request.GetRequestStream()))
  284. // {
  285. // sw.Write(param.Trim('&'));
  286. // sw.Close();
  287. // }
  288. // }
  289. // var res = request.GetResponse() as HttpWebResponse;
  290. // var st = res.GetResponseStream();
  291. // var sr = new StreamReader(st);
  292. // return sr.ReadToEnd();
  293. //}
  294. #endregion
  295. }
  296. }