版博士V2.0程序
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HttpUtil.CS 8.9 KiB

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