【httplistener监听获取Post请求参数】

喜欢ヅ旅行 2022-09-21 14:26 304阅读 0赞

使用httplistener监听来自客户端的http请求,对于Get请求的数据可以通过Request.QueryString[“参数”]获取

而对于来自客户端的Post请求则不能使用Request[“”]获取,需要将获取分析请求流中的数据拿到参数

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace HttpListenerPost
  9. {
  10. /// <summary>
  11. /// HttpListenner监听Post请求参数值实体
  12. /// </summary>
  13. public class HttpListenerPostValue
  14. {
  15. /// <summary>
  16. /// 0=> 参数
  17. /// 1=> 文件
  18. /// </summary>
  19. public int type = 0;
  20. public string name;
  21. public byte[] datas;
  22. }
  23. /// <summary>
  24. /// 获取Post请求中的参数和值帮助类
  25. /// </summary>
  26. public class HttpListenerPostParaHelper
  27. {
  28. private HttpListenerContext request;
  29. public HttpListenerPostParaHelper(HttpListenerContext request)
  30. {
  31. this.request = request;
  32. }
  33. private bool CompareBytes(byte[] source, byte[] comparison)
  34. {
  35. try
  36. {
  37. int count = source.Length;
  38. if (source.Length != comparison.Length)
  39. return false;
  40. for (int i = 0; i < count; i++)
  41. if (source[i] != comparison[i])
  42. return false;
  43. return true;
  44. }
  45. catch
  46. {
  47. return false;
  48. }
  49. }
  50. private byte[] ReadLineAsBytes(Stream SourceStream)
  51. {
  52. var resultStream = new MemoryStream();
  53. while (true)
  54. {
  55. int data = SourceStream.ReadByte();
  56. resultStream.WriteByte((byte)data);
  57. if (data == 10)
  58. break;
  59. }
  60. resultStream.Position = 0;
  61. byte[] dataBytes = new byte[resultStream.Length];
  62. resultStream.Read(dataBytes, 0, dataBytes.Length);
  63. return dataBytes;
  64. }
  65. /// <summary>
  66. /// 获取Post过来的参数和数据
  67. /// </summary>
  68. /// <returns></returns>
  69. public List<HttpListenerPostValue> GetHttpListenerPostValue()
  70. {
  71. try
  72. {
  73. List<HttpListenerPostValue> HttpListenerPostValueList = new List<HttpListenerPostValue>();
  74. if (request.Request.ContentType.Length > 20 && string.Compare(request.Request.ContentType.Substring(0, 20), "multipart/form-data;", true) == 0)
  75. {
  76. string[] HttpListenerPostValue = request.Request.ContentType.Split(';').Skip(1).ToArray();
  77. string boundary = string.Join(";", HttpListenerPostValue).Replace("boundary=", "").Trim();
  78. byte[] ChunkBoundary = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  79. byte[] EndBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  80. Stream SourceStream = request.Request.InputStream;
  81. var resultStream = new MemoryStream();
  82. bool CanMoveNext = true;
  83. HttpListenerPostValue data = null;
  84. while (CanMoveNext)
  85. {
  86. byte[] currentChunk = ReadLineAsBytes(SourceStream);
  87. if (!Encoding.UTF8.GetString(currentChunk).Equals("\r\n"))
  88. resultStream.Write(currentChunk, 0, currentChunk.Length);
  89. if (CompareBytes(ChunkBoundary, currentChunk))
  90. {
  91. byte[] result = new byte[resultStream.Length - ChunkBoundary.Length];
  92. resultStream.Position = 0;
  93. resultStream.Read(result, 0, result.Length);
  94. CanMoveNext = true;
  95. if (result.Length > 0)
  96. data.datas = result;
  97. data = new HttpListenerPostValue();
  98. HttpListenerPostValueList.Add(data);
  99. resultStream.Dispose();
  100. resultStream = new MemoryStream();
  101. }
  102. else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Disposition"))
  103. {
  104. byte[] result = new byte[resultStream.Length - 2];
  105. resultStream.Position = 0;
  106. resultStream.Read(result, 0, result.Length);
  107. CanMoveNext = true;
  108. data.name = Encoding.UTF8.GetString(result).Replace("Content-Disposition: form-data; name=\"", "").Replace("\"", "").Split(';')[0];
  109. resultStream.Dispose();
  110. resultStream = new MemoryStream();
  111. }
  112. else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Type"))
  113. {
  114. CanMoveNext = true;
  115. data.type = 1;
  116. resultStream.Dispose();
  117. resultStream = new MemoryStream();
  118. }
  119. else if (CompareBytes(EndBoundary, currentChunk))
  120. {
  121. byte[] result = new byte[resultStream.Length - EndBoundary.Length - 2];
  122. resultStream.Position = 0;
  123. resultStream.Read(result, 0, result.Length);
  124. data.datas = result;
  125. resultStream.Dispose();
  126. CanMoveNext = false;
  127. }
  128. }
  129. }
  130. return HttpListenerPostValueList;
  131. }
  132. catch (Exception ex)
  133. {
  134. return null;
  135. }
  136. }
  137. }
  138. }

开启监听,获取Post请求的参数

  1. class Program
  2. {
  3. private static HttpListener httpPostRequest = new HttpListener();
  4. static void Main(string[] args)
  5. {
  6. httpPostRequest.Prefixes.Add("http://10.0.0.217:30000/posttype/");
  7. httpPostRequest.Start();
  8. Thread ThrednHttpPostRequest = new Thread(new ThreadStart(httpPostRequestHandle));
  9. ThrednHttpPostRequest.Start();
  10. }
  11. private static void httpPostRequestHandle()
  12. {
  13. while (true)
  14. {
  15. HttpListenerContext requestContext = httpPostRequest.GetContext();
  16. Thread threadsub = new Thread(new ParameterizedThreadStart((requestcontext) =>
  17. {
  18. HttpListenerContext request = (HttpListenerContext)requestcontext;
  19. //获取Post请求中的参数和值帮助类
  20. HttpListenerPostParaHelper httppost=new HttpListenerPostParaHelper (request);
  21. //获取Post过来的参数和数据
  22. List<HttpListenerPostValue> lst=httppost.GetHttpListenerPostValue();
  23. string userName = "";
  24. string password = "";
  25. string suffix = "";
  26. string adType = "";
  27. //使用方法
  28. foreach (var key in lst)
  29. {
  30. if (key.type == 0)
  31. {
  32. string value = Encoding.UTF8.GetString(key.datas).Replace("\r\n", "");
  33. if (key.name == "username")
  34. {
  35. userName = value;
  36. Console.WriteLine(value);
  37. }
  38. if (key.name == "password")
  39. {
  40. password = value;
  41. Console.WriteLine(value);
  42. }
  43. if (key.name == "suffix")
  44. {
  45. suffix = value;
  46. Console.WriteLine(value);
  47. }
  48. if (key.name == "adtype")
  49. {
  50. adType = value;
  51. Console.WriteLine(value);
  52. }
  53. }
  54. if (key.type == 1)
  55. {
  56. string fileName = request.Request.QueryString["FileName"];
  57. if (!string.IsNullOrEmpty(fileName))
  58. {
  59. string filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyMMdd_HHmmss_ffff") + Path.GetExtension(fileName).ToLower();
  60. if (key.name == "File")
  61. {
  62. FileStream fs = new FileStream(filePath, FileMode.Create);
  63. fs.Write(key.datas, 0, key.datas.Length);
  64. fs.Close();
  65. fs.Dispose();
  66. }
  67. }
  68. }
  69. }
  70. //Response
  71. request.Response.StatusCode = 200;
  72. request.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  73. request.Response.ContentType = "application/json";
  74. requestContext.Response.ContentEncoding = Encoding.UTF8;
  75. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new {success="true",msg="提交成功" }));
  76. request.Response.ContentLength64 = buffer.Length;
  77. var output = request.Response.OutputStream;
  78. output.Write(buffer, 0, buffer.Length);
  79. output.Close();
  80. }));
  81. threadsub.Start(requestContext);
  82. }
  83. }

使用谷歌请求插件进行post请求,上传了文件,获取到了post参数.
20160623143604191

发表评论

表情:
评论列表 (有 0 条评论,304人围观)

还没有评论,来说两句吧...

相关阅读