版博士V2.0程序
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

249 rader
10 KiB

  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Net.NetworkInformation;
  9. using System.Net.Sockets;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Web;
  14. namespace ProductionControl.Utils
  15. {
  16. internal static class HttpUtil
  17. {
  18. /// <summary>
  19. /// 获取本机IP地址列表
  20. /// </summary>
  21. /// <param name="_type">Wireless80211:本地所有IP(仅127.0.0.1);Ethernet:仅获取以太网接口的 IP 地址</param>
  22. public static List<string> getLocalIPList(NetworkInterfaceType _type= NetworkInterfaceType.Unknown)
  23. {
  24. List<string> output = new List<string>();
  25. foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
  26. {
  27. if ((_type == NetworkInterfaceType.Unknown || item.NetworkInterfaceType == _type) && item.OperationalStatus == OperationalStatus.Up)
  28. {
  29. foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
  30. {
  31. if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
  32. {
  33. API.OutputDebugString($"{item.NetworkInterfaceType.ToString()}; {ip.Address.AddressFamily.ToString()}; {ip.Address.ToString()}");
  34. output.Add(ip.Address.ToString());
  35. }
  36. }
  37. }
  38. }
  39. return output;
  40. }
  41. //读取请求数据
  42. public static string getPostData(HttpListenerRequest request)
  43. {
  44. if (!request.HasEntityBody)
  45. return null;
  46. string result;
  47. using (Stream inputStream = request.InputStream)
  48. {
  49. using (StreamReader streamReader = new StreamReader(inputStream, Encoding.UTF8))
  50. result = streamReader.ReadToEnd();
  51. }
  52. return result;
  53. }
  54. /// <summary>
  55. /// POST请求接口调用
  56. /// </summary>
  57. /// <param name="url"></param>
  58. /// <param name="json"></param>
  59. /// <returns></returns>
  60. public static void post(string url, string json, Action<JObject> callBack = null)
  61. {
  62. System.Threading.ThreadPool.QueueUserWorkItem(
  63. new WaitCallback(o =>
  64. {
  65. var data = (JObject)o;
  66. if (callBack == null)
  67. postSync(data["url"].ToString(), data["json"].ToString(), false);
  68. else
  69. callBack(postSync(data["url"].ToString(), data["json"].ToString()));
  70. }),
  71. JObject.FromObject(new { url, json })
  72. );
  73. }
  74. //HttpWebRequest方式
  75. public static JObject postSync2(string url, string json, bool recvResp = true)
  76. {
  77. JObject resp = new JObject();
  78. try
  79. {
  80. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  81. request.Method = "POST";
  82. //request.ContentType = "application/x-www-form-urlencoded";
  83. request.ContentType = "application /json";
  84. StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.UTF8);
  85. requestWriter.Write(json);
  86. requestWriter.Flush();
  87. requestWriter.Close();
  88. if (recvResp)
  89. {
  90. WebResponse webResponse = request.GetResponse();
  91. Stream webStream = webResponse.GetResponseStream();
  92. StreamReader responseReader = new StreamReader(webStream);
  93. resp.Add("data", responseReader.ReadToEnd());
  94. resp.Add("success", true);
  95. }
  96. else
  97. {
  98. request.GetResponse().Close();//必需调用此GetResponse后上面的write才会发送出去,操
  99. resp.Add("data", "");
  100. resp.Add("success", true);
  101. }
  102. }
  103. catch (Exception ex)
  104. {
  105. resp.Add("success", false);
  106. resp.Add("data", ex.Message);
  107. }
  108. return resp;
  109. }
  110. //HttpClient方式
  111. public static JObject postSync(string url, string json, bool recvResp = true, bool isJson = false)
  112. {
  113. JObject resp = new JObject();
  114. try
  115. {
  116. HttpClient http = new HttpClient();
  117. StringContent dataContent;
  118. //第一种方式:data是json格式
  119. if (isJson)
  120. dataContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); // {"PageNum":"1","PageSIze":"20","info":"311011500300661"}
  121. else
  122. {
  123. // 第二种方式:form表单提交 内容post 提交都在StringContent请求body中添加
  124. string lsUrlEncodeStr = json2Params(JObject.Parse(json));
  125. dataContent = new StringContent(lsUrlEncodeStr, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"); //PageNum=1&PageSize=20&info=311011500300661
  126. }
  127. http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "token");
  128. var taskstr = http.PostAsync(url, dataContent).Result.Content.ReadAsStringAsync();
  129. API.OutputDebugString("wlq postSync:url=" + url + ";resp=" + taskstr.Result);
  130. //读取返回数据
  131. //return taskstr.Result;
  132. if (recvResp)
  133. {
  134. resp.Add("data", taskstr.Result);
  135. resp.Add("success", true);
  136. }
  137. else
  138. {
  139. resp.Add("data", "");
  140. resp.Add("success", true);
  141. }
  142. }
  143. catch (Exception ex)
  144. {
  145. resp.Add("success", false);
  146. resp.Add("data", ex.Message);
  147. }
  148. return resp;
  149. }
  150. /// <summary>
  151. /// 向HTTP连接写入数据
  152. /// </summary>
  153. /// <param name="resp">HttpListenerContext.Response</param>
  154. /// <param name="data"></param>
  155. /// <returns>如果连接关闭返回 false</returns>
  156. public static bool writeToHttpContext(HttpListenerResponse resp, byte[] dataBuff)
  157. {
  158. try
  159. {
  160. resp.OutputStream.Write(dataBuff, 0, dataBuff.Length);
  161. resp.OutputStream.Flush();
  162. return true;
  163. }
  164. catch (Exception ex)
  165. {
  166. return false;
  167. }
  168. }
  169. public static bool writeToHttpContext_json(HttpListenerResponse resp, string json)
  170. {
  171. byte[] buff = Encoding.UTF8.GetBytes(json);
  172. resp.ContentType = "application/json";
  173. resp.ContentEncoding = Encoding.UTF8;
  174. return writeToHttpContext(resp, buff);
  175. }
  176. public static bool writeToHttpContext_text(HttpListenerResponse resp, string text)
  177. {
  178. byte[] buff = Encoding.UTF8.GetBytes(text);
  179. resp.ContentType = "application/text";
  180. resp.ContentEncoding = Encoding.UTF8;
  181. return writeToHttpContext(resp, buff);
  182. }
  183. private static string json2Params(JObject json)
  184. {
  185. string result = "";
  186. IEnumerable<JProperty> properties = json.Properties();
  187. foreach (JProperty item in properties)
  188. {
  189. result += item.Name.ToString() + "=" + item.Value.ToString() + "&";
  190. // item.Name 为 键
  191. // item.Value 为 值
  192. }
  193. result = result.Substring(0, result.Length - 1);
  194. //string result1 = WebUtility.UrlEncode(result);//转义字符大写
  195. ////string result2 = HttpUtility.UrlEncode(result);//转义字符小写
  196. return result;
  197. }
  198. /// <summary>
  199. /// 获取文件对应MIME类型
  200. /// </summary>
  201. /// <param name="fileExtention">文件扩展名,如.jpg</param>
  202. /// <returns></returns>
  203. public static string GetContentType(string fileExtention)
  204. {
  205. if (string.Compare(fileExtention, ".html", true) == 0 || string.Compare(fileExtention, ".htm", true) == 0)
  206. return "text/html;charset=utf-8";
  207. else if (string.Compare(fileExtention, ".js", true) == 0)
  208. return "application/javascript";
  209. else if (string.Compare(fileExtention, ".css", true) == 0)
  210. return "text/css";
  211. else if (string.Compare(fileExtention, ".png", true) == 0)
  212. return "image/png";
  213. else if (string.Compare(fileExtention, ".jpg", true) == 0 || string.Compare(fileExtention, ".jpeg", true) == 0)
  214. return "image/jpeg";
  215. else if (string.Compare(fileExtention, ".gif", true) == 0)
  216. return "image/gif";
  217. else if (string.Compare(fileExtention, ".swf", true) == 0)
  218. return "application/x-shockwave-flash";
  219. else if (string.Compare(fileExtention, ".bcmap", true) == 0)
  220. return "image/svg+xml";
  221. else if (string.Compare(fileExtention, ".properties", true) == 0)
  222. return "application/octet-stream";
  223. else if (string.Compare(fileExtention, ".map", true) == 0)
  224. return "text/plain";
  225. else if (string.Compare(fileExtention, ".svg", true) == 0)
  226. return "image/svg+xml";
  227. else if (string.Compare(fileExtention, ".pdf", true) == 0)
  228. return "application/pdf";
  229. else if (string.Compare(fileExtention, ".txt", true) == 0)
  230. return "text/*";
  231. else if (string.Compare(fileExtention, ".dat", true) == 0)
  232. return "text/*";
  233. else
  234. return "application/octet-stream";//application/octet-stream
  235. }
  236. }
  237. }