HttpRequest.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.Sockets;
  7. using System.IO;
  8. using System.Text.RegularExpressions;
  9. namespace ServerLib
  10. {
  11. /// <summary>
  12. /// HTTP请求定义
  13. /// </summary>
  14. public class HttpRequest : BaseHeader
  15. {
  16. /// <summary>
  17. /// URL参数
  18. /// </summary>
  19. public Object Params { get; private set; }
  20. /// <summary>
  21. /// HTTP请求方式
  22. /// </summary>
  23. public string Method { get; private set; }
  24. /// <summary>
  25. /// HTTP(S)地址
  26. /// </summary>
  27. public string URL { get; set; }
  28. /// <summary>
  29. /// HTTP协议版本
  30. /// </summary>
  31. public string ProtocolVersion { get; set; }
  32. /// <summary>
  33. /// 定义缓冲区
  34. /// </summary>
  35. private const int MAX_SIZE = 1024 * 1024 * 2;
  36. private byte[] bytes = new byte[MAX_SIZE];
  37. public ILogger Logger { get; set; }
  38. private Stream handler;
  39. public HttpRequest(Stream stream)
  40. {
  41. this.handler = stream;
  42. var data = GetRequestData(handler);
  43. var rows = Regex.Split(data, Environment.NewLine);
  44. //Request URL & Method & Version
  45. var first = Regex.Split(rows[0], @"(\s+)")
  46. .Where(e => e.Trim() != string.Empty)
  47. .ToArray();
  48. if (first.Length > 0) this.Method = first[0];
  49. if (first.Length > 1) this.URL = Uri.UnescapeDataString(first[1]);
  50. if (first.Length > 2) this.ProtocolVersion = first[2];
  51. //Request Headers
  52. this.Headers = GetRequestHeaders(rows);
  53. //Request Body
  54. Body = GetRequestBody(rows);
  55. var contentLength = GetHeader(RequestHeaders.ContentLength);
  56. if (int.TryParse(contentLength, out var length) && Body.Length != length)
  57. {
  58. do
  59. {
  60. length = stream.Read(bytes, 0, MAX_SIZE - 1);
  61. Body += Encoding.UTF8.GetString(bytes, 0, length);
  62. } while (Body.Length != length);
  63. }
  64. //Request "GET"
  65. if (this.Method == "GET")
  66. {
  67. var isUrlencoded = this.URL.Contains('?');
  68. if (isUrlencoded) this.Params = GetRequestParameters(URL.Split('?')[1]);
  69. }
  70. //Request "POST"
  71. if (this.Method == "POST")
  72. {
  73. var contentType = GetHeader(RequestHeaders.ContentType);
  74. if (contentType == @"application/x-www-form-urlencoded")
  75. this.Params = GetRequestParameters(this.Body);
  76. else if (contentType.Contains("application/json")) //application/json;charset=UTF-8
  77. this.Params = (this.Body);
  78. }
  79. }
  80. public Stream GetRequestStream()
  81. {
  82. return this.handler;
  83. }
  84. public string GetHeader(RequestHeaders header)
  85. {
  86. return GetHeaderByKey(header);
  87. }
  88. public string GetHeader(string fieldName)
  89. {
  90. return GetHeaderByKey(fieldName);
  91. }
  92. public void SetHeader(RequestHeaders header, string value)
  93. {
  94. SetHeaderByKey(header, value);
  95. }
  96. public void SetHeader(string fieldName, string value)
  97. {
  98. SetHeaderByKey(fieldName, value);
  99. }
  100. private string GetRequestData(Stream stream)
  101. {
  102. var length = 0;
  103. var data = string.Empty;
  104. do
  105. {
  106. length = stream.Read(bytes, 0, MAX_SIZE - 1);
  107. data += Encoding.UTF8.GetString(bytes, 0, length);
  108. } while (length > 0 && !data.Contains("\r\n\r\n"));
  109. return data;
  110. }
  111. private string GetRequestBody(IEnumerable<string> rows)
  112. {
  113. var target = rows.Select((v, i) => new { Value = v, Index = i })
  114. .FirstOrDefault(e => e.Value.Trim() == string.Empty);
  115. if (target == null) return null;
  116. var range = Enumerable.Range(target.Index + 1, rows.Count() - target.Index - 1);
  117. return string.Join(Environment.NewLine, range.Select(e => rows.ElementAt(e)).ToArray());
  118. }
  119. private Dictionary<string, string> GetRequestHeaders(IEnumerable<string> rows)
  120. {
  121. if (rows == null || rows.Count() <= 0) return null;
  122. var target = rows.Select((v, i) => new { Value = v, Index = i })
  123. .FirstOrDefault(e => e.Value.Trim() == string.Empty);
  124. var length = target == null ? rows.Count() - 1 : target.Index;
  125. if (length <= 1) return null;
  126. var range = Enumerable.Range(1, length - 1);
  127. return range.Select(e => rows.ElementAt(e)).ToDictionary(e => e.Split(':')[0], e => e.Split(':')[1].Trim());
  128. }
  129. private Dictionary<string, string> GetRequestParameters(string row)
  130. {
  131. if (string.IsNullOrEmpty(row)) return null;
  132. var kvs = Regex.Split(row, "&");
  133. if (kvs == null || kvs.Count() <= 0) return null;
  134. return kvs.ToDictionary(e => Regex.Split(e, "=")[0], e =>
  135. {
  136. var p = Regex.Split(e, "=");
  137. return p.Length > 1 ? p[1] : "";
  138. });
  139. }
  140. }
  141. }