革博士程序V1仓库
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.

HttpUtil.CS 10 KiB

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