HttpRequest.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. //------------------------------------------------------------------------------
  2. // 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有
  3. // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权
  4. // CSDN博客:https://blog.csdn.net/qq_40374647
  5. // 哔哩哔哩视频:https://space.bilibili.com/94253567
  6. // Gitee源代码仓库:https://gitee.com/RRQM_Home
  7. // Github源代码仓库:https://github.com/RRQM
  8. // API首页:https://www.yuque.com/rrqm/touchsocket/index
  9. // 交流QQ群:234762506
  10. // 感谢您的下载和使用
  11. //------------------------------------------------------------------------------
  12. //------------------------------------------------------------------------------
  13. using System;
  14. using System.Collections.Specialized;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Text.RegularExpressions;
  19. using TouchSocket.Core;
  20. using TouchSocket.Sockets;
  21. namespace TouchSocket.Http
  22. {
  23. /// <summary>
  24. /// HTTP请求定义
  25. /// </summary>
  26. public class HttpRequest : HttpBase
  27. {
  28. private bool m_canRead;
  29. private ITcpClientBase m_client;
  30. private byte[] m_content;
  31. private NameValueCollection m_forms;
  32. private NameValueCollection m_params;
  33. private NameValueCollection m_query;
  34. private string m_relativeURL;
  35. private bool m_sentHeader;
  36. private int m_sentLength;
  37. private string m_uRL;
  38. /// <summary>
  39. /// 构造函数
  40. /// </summary>
  41. /// <param name="client"></param>
  42. /// <param name="isServer"></param>
  43. public HttpRequest(ITcpClientBase client, bool isServer = false)
  44. {
  45. m_client = client;
  46. if (isServer)
  47. {
  48. m_canRead = true;
  49. CanWrite = false;
  50. }
  51. else
  52. {
  53. m_canRead = false;
  54. CanWrite = true;
  55. }
  56. }
  57. /// <summary>
  58. /// 构造函数
  59. /// </summary>
  60. public HttpRequest()
  61. {
  62. m_canRead = false;
  63. CanWrite = false;
  64. }
  65. /// <summary>
  66. /// <inheritdoc/>
  67. /// </summary>
  68. public override bool CanRead => m_canRead;
  69. /// <summary>
  70. /// <inheritdoc/>
  71. /// </summary>
  72. public override bool CanWrite { get; }
  73. /// <summary>
  74. /// <inheritdoc/>
  75. /// </summary>
  76. public override ITcpClientBase Client => m_client;
  77. /// <summary>
  78. /// 表单数据
  79. /// </summary>
  80. public NameValueCollection Forms
  81. {
  82. get
  83. {
  84. if (ContentType == @"application/x-www-form-urlencoded")
  85. {
  86. m_forms ??= GetParameters(this.GetBody());
  87. return m_forms;
  88. }
  89. return m_forms ??= new NameValueCollection();
  90. }
  91. }
  92. /// <summary>
  93. /// 获取时候保持连接
  94. /// </summary>
  95. public bool KeepAlive
  96. {
  97. get
  98. {
  99. if (ProtocolVersion == "1.0")
  100. {
  101. return false;
  102. }
  103. else
  104. {
  105. if (GetHeader(HttpHeaders.Connection) == "keep-alive")
  106. {
  107. return true;
  108. }
  109. else
  110. {
  111. return false;
  112. }
  113. }
  114. }
  115. }
  116. /// <summary>
  117. /// HTTP请求方式。
  118. /// </summary>
  119. public string Method { get; set; }
  120. /// <summary>
  121. /// Body参数
  122. /// </summary>
  123. public NameValueCollection Params
  124. {
  125. get
  126. {
  127. m_params ??= new NameValueCollection();
  128. return m_params;
  129. }
  130. }
  131. /// <summary>
  132. /// url参数
  133. /// </summary>
  134. public NameValueCollection Query
  135. {
  136. get
  137. {
  138. m_query ??= new NameValueCollection();
  139. return m_query;
  140. }
  141. }
  142. /// <summary>
  143. /// 相对路径(不含参数)
  144. /// </summary>
  145. public string RelativeURL => m_relativeURL;
  146. /// <summary>
  147. /// Url全地址,包含参数
  148. /// </summary>
  149. public string URL => m_uRL;
  150. /// <summary>
  151. /// 构建响应数据。
  152. /// <para>当数据较大时,不建议这样操作,可直接<see cref="WriteContent(byte[], int, int)"/></para>
  153. /// </summary>
  154. /// <param name="byteBlock"></param>
  155. public void Build(ByteBlock byteBlock)
  156. {
  157. BuildHeader(byteBlock);
  158. BuildContent(byteBlock);
  159. }
  160. /// <summary>
  161. /// 构建数据为字节数组。
  162. /// </summary>
  163. /// <returns></returns>
  164. public byte[] BuildAsBytes()
  165. {
  166. using ByteBlock byteBlock = new ByteBlock();
  167. Build(byteBlock);
  168. return byteBlock.ToArray();
  169. }
  170. /// <summary>
  171. /// 设置内容
  172. /// </summary>
  173. /// <param name="content"></param>
  174. public override void SetContent(byte[] content)
  175. {
  176. m_content = content;
  177. ContentLength = content.Length;
  178. ContentComplated = true;
  179. }
  180. /// <summary>
  181. /// 设置Url,必须以“/”开头,可带参数
  182. /// </summary>
  183. /// <param name="url"></param>
  184. /// <param name="justValue"></param>
  185. /// <returns></returns>
  186. public HttpRequest SetUrl(string url, bool justValue = false)
  187. {
  188. if (justValue || url.StartsWith("/"))
  189. {
  190. m_uRL = url;
  191. }
  192. else
  193. {
  194. m_uRL = "/" + url;
  195. }
  196. ParseUrl();
  197. return this;
  198. }
  199. /// <summary>
  200. /// 输出
  201. /// </summary>
  202. public override string ToString()
  203. {
  204. using (ByteBlock byteBlock = new ByteBlock())
  205. {
  206. Build(byteBlock);
  207. return byteBlock.ToString();
  208. }
  209. }
  210. /// <summary>
  211. /// <inheritdoc/>
  212. /// </summary>
  213. /// <returns></returns>
  214. public override bool TryGetContent(out byte[] content)
  215. {
  216. if (!ContentComplated.HasValue)
  217. {
  218. if (m_contentLength == 0)
  219. {
  220. m_content = new byte[0];
  221. content = m_content;
  222. ContentComplated = true;
  223. return true;
  224. }
  225. try
  226. {
  227. using MemoryStream block1 = new MemoryStream();
  228. using ByteBlock block2 = new ByteBlock();
  229. byte[] buffer = block2.Buffer;
  230. while (true)
  231. {
  232. int r = Read(buffer, 0, buffer.Length);
  233. if (r == 0)
  234. {
  235. break;
  236. }
  237. block1.Write(buffer, 0, r);
  238. }
  239. ContentComplated = true;
  240. m_content = block1.ToArray();
  241. content = m_content;
  242. return true;
  243. }
  244. catch
  245. {
  246. ContentComplated = false;
  247. content = null;
  248. return false;
  249. }
  250. finally
  251. {
  252. m_canRead = false;
  253. }
  254. }
  255. else if (ContentComplated == true)
  256. {
  257. content = m_content;
  258. return true;
  259. }
  260. else
  261. {
  262. content = null;
  263. return false;
  264. }
  265. }
  266. /// <summary>
  267. /// <inheritdoc/>
  268. /// </summary>
  269. /// <param name="buffer"></param>
  270. /// <param name="offset"></param>
  271. /// <param name="count"></param>
  272. public override void WriteContent(byte[] buffer, int offset, int count)
  273. {
  274. if (!CanWrite)
  275. {
  276. throw new NotSupportedException("该对象不支持持续写入内容。");
  277. }
  278. if (!m_sentHeader)
  279. {
  280. using (ByteBlock byteBlock = new ByteBlock())
  281. {
  282. BuildHeader(byteBlock);
  283. m_client.DefaultSend(byteBlock);
  284. }
  285. m_sentHeader = true;
  286. }
  287. if (m_sentLength + count <= m_contentLength)
  288. {
  289. m_client.DefaultSend(buffer, offset, count);
  290. m_sentLength += count;
  291. }
  292. }
  293. /// <summary>
  294. /// <inheritdoc/>
  295. /// </summary>
  296. /// <param name="disposing"></param>
  297. protected override void Dispose(bool disposing)
  298. {
  299. m_client = null;
  300. base.Dispose(disposing);
  301. }
  302. /// <summary>
  303. /// 从内存中读取
  304. /// </summary>
  305. protected override void LoadHeaderProterties()
  306. {
  307. var first = Regex.Split(RequestLine, @"(\s+)").Where(e => e.Trim() != string.Empty).ToArray();
  308. if (first.Length > 0) Method = first[0].Trim().ToUpper();
  309. if (first.Length > 1)
  310. {
  311. SetUrl(Uri.UnescapeDataString(first[1]));
  312. }
  313. if (first.Length > 2)
  314. {
  315. string[] ps = first[2].Split('/');
  316. if (ps.Length == 2)
  317. {
  318. Protocols = ps[0];
  319. ProtocolVersion = ps[1];
  320. }
  321. }
  322. }
  323. private void BuildContent(ByteBlock byteBlock)
  324. {
  325. if (ContentLength > 0)
  326. {
  327. byteBlock.Write(m_content);
  328. }
  329. }
  330. /// <summary>
  331. /// 构建响应头部
  332. /// </summary>
  333. /// <returns></returns>
  334. private void BuildHeader(ByteBlock byteBlock)
  335. {
  336. StringBuilder stringBuilder = new StringBuilder();
  337. string url = null;
  338. if (!string.IsNullOrEmpty(m_relativeURL))
  339. {
  340. if (m_query == null)
  341. {
  342. url = m_relativeURL;
  343. }
  344. else
  345. {
  346. StringBuilder urlBuilder = new StringBuilder();
  347. urlBuilder.Append(m_relativeURL);
  348. urlBuilder.Append("?");
  349. int i = 0;
  350. foreach (var item in m_query.AllKeys)
  351. {
  352. urlBuilder.Append($"{item}={m_query[item]}");
  353. if (++i < m_query.Count)
  354. {
  355. urlBuilder.Append("&");
  356. }
  357. }
  358. url = urlBuilder.ToString();
  359. }
  360. }
  361. if (string.IsNullOrEmpty(url))
  362. {
  363. stringBuilder.Append($"{Method} / HTTP/{ProtocolVersion}\r\n");
  364. }
  365. else
  366. {
  367. stringBuilder.Append($"{Method} {url} HTTP/{ProtocolVersion}\r\n");
  368. }
  369. if (ContentLength > 0)
  370. {
  371. this.SetHeader(HttpHeaders.ContentLength, ContentLength.ToString());
  372. }
  373. foreach (var headerkey in Headers.AllKeys)
  374. {
  375. stringBuilder.Append($"{headerkey}: ");
  376. stringBuilder.Append(Headers[headerkey] + "\r\n");
  377. }
  378. stringBuilder.Append("\r\n");
  379. byteBlock.Write(Encoding.UTF8.GetBytes(stringBuilder.ToString()));
  380. }
  381. private NameValueCollection GetParameters(string row)
  382. {
  383. if (string.IsNullOrEmpty(row))
  384. {
  385. return null;
  386. }
  387. string[] kvs = row.Split('&');
  388. if (kvs == null || kvs.Count() == 0)
  389. {
  390. return null;
  391. }
  392. NameValueCollection pairs = new NameValueCollection();
  393. foreach (var item in kvs)
  394. {
  395. string[] kv = item.SplitFirst('=');
  396. if (kv.Length == 2)
  397. {
  398. pairs.Add(kv[0], kv[1]);
  399. }
  400. }
  401. return pairs;
  402. }
  403. private void ParseUrl()
  404. {
  405. if (m_uRL.Contains("?"))
  406. {
  407. string[] urls = m_uRL.Split('?');
  408. if (urls.Length > 0)
  409. {
  410. m_relativeURL = urls[0];
  411. }
  412. if (urls.Length > 1)
  413. {
  414. m_query = GetParameters(urls[1]);
  415. }
  416. }
  417. else
  418. {
  419. m_relativeURL = m_uRL;
  420. }
  421. }
  422. }
  423. }