C# 接收http请求

不想你离开。 提交于 2019-12-17 20:03:30

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

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

using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Net;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace HttpListenerPost  
{  
    /// <summary>  
    /// HttpListenner监听Post请求参数值实体  
    /// </summary>  
    public class HttpListenerPostValue  
    {  
        /// <summary>  
        /// 0=> 参数  
        /// 1=> 文件  
        /// </summary>  
        public int type = 0;  
        public string name;  
        public byte[] datas;  
    }  
  
    /// <summary>  
    /// 获取Post请求中的参数和值帮助类  
    /// </summary>  
    public class HttpListenerPostParaHelper  
    {  
        private HttpListenerContext request;  
  
        public HttpListenerPostParaHelper(HttpListenerContext request)  
        {  
            this.request = request;  
        }  
  
        private bool CompareBytes(byte[] source, byte[] comparison)  
        {  
            try  
            {  
                int count = source.Length;  
                if (source.Length != comparison.Length)  
                    return false;  
                for (int i = 0; i < count; i++)  
                    if (source[i] != comparison[i])  
                        return false;  
                return true;  
            }  
            catch  
            {  
                return false;  
            }  
        }  
  
        private byte[] ReadLineAsBytes(Stream SourceStream)  
        {  
            var resultStream = new MemoryStream();  
            while (true)  
            {  
                int data = SourceStream.ReadByte();  
                resultStream.WriteByte((byte)data);  
                if (data == 10)  
                    break;  
            }  
            resultStream.Position = 0;  
            byte[] dataBytes = new byte[resultStream.Length];  
            resultStream.Read(dataBytes, 0, dataBytes.Length);  
            return dataBytes;  
        }  
  
        /// <summary>  
        /// 获取Post过来的参数和数据  
        /// </summary>  
        /// <returns></returns>  
        public List<HttpListenerPostValue> GetHttpListenerPostValue()  
        {  
            try  
            {  
                List<HttpListenerPostValue> HttpListenerPostValueList = new List<HttpListenerPostValue>();  
                if (request.Request.ContentType.Length > 20 && string.Compare(request.Request.ContentType.Substring(0, 20), "multipart/form-data;", true) == 0)  
                {  
                    string[] HttpListenerPostValue = request.Request.ContentType.Split(';').Skip(1).ToArray();  
                    string boundary = string.Join(";", HttpListenerPostValue).Replace("boundary=", "").Trim();  
                    byte[] ChunkBoundary = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");  
                    byte[] EndBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");  
                    Stream SourceStream = request.Request.InputStream;  
                    var resultStream = new MemoryStream();  
                    bool CanMoveNext = true;  
                    HttpListenerPostValue data = null;  
                    while (CanMoveNext)  
                    {  
                        byte[] currentChunk = ReadLineAsBytes(SourceStream);  
                        if (!Encoding.UTF8.GetString(currentChunk).Equals("\r\n"))  
                            resultStream.Write(currentChunk, 0, currentChunk.Length);  
                        if (CompareBytes(ChunkBoundary, currentChunk))  
                        {  
                            byte[] result = new byte[resultStream.Length - ChunkBoundary.Length];  
                            resultStream.Position = 0;  
                            resultStream.Read(result, 0, result.Length);  
                            CanMoveNext = true;  
                            if (result.Length > 0)  
                                data.datas = result;  
                            data = new HttpListenerPostValue();  
                            HttpListenerPostValueList.Add(data);  
                            resultStream.Dispose();  
                            resultStream = new MemoryStream();  
  
                        }  
                        else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Disposition"))  
                        {  
                            byte[] result = new byte[resultStream.Length - 2];  
                            resultStream.Position = 0;  
                            resultStream.Read(result, 0, result.Length);  
                            CanMoveNext = true;  
                            data.name = Encoding.UTF8.GetString(result).Replace("Content-Disposition: form-data; name=\"", "").Replace("\"", "").Split(';')[0];  
                            resultStream.Dispose();  
                            resultStream = new MemoryStream();  
                        }  
                        else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Type"))  
                        {  
                            CanMoveNext = true;  
                            data.type = 1;  
                            resultStream.Dispose();  
                            resultStream = new MemoryStream();  
                        }  
                        else if (CompareBytes(EndBoundary, currentChunk))  
                        {  
                            byte[] result = new byte[resultStream.Length - EndBoundary.Length - 2];  
                            resultStream.Position = 0;  
                            resultStream.Read(result, 0, result.Length);  
                            data.datas = result;  
                            resultStream.Dispose();  
                            CanMoveNext = false;  
                        }  
                    }  
                }  
                return HttpListenerPostValueList;  
            }  
            catch (Exception ex)  
            {  
                return null;  
            }  
        }  
    }  
}

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

class Program  
   {  
       private static HttpListener httpPostRequest = new HttpListener();  
  
       static void Main(string[] args)  
       {  
           httpPostRequest.Prefixes.Add("http://10.0.0.217:30000/posttype/");  
           httpPostRequest.Start();  
  
           Thread ThrednHttpPostRequest = new Thread(new ThreadStart(httpPostRequestHandle));  
           ThrednHttpPostRequest.Start();  
       }  
  
       private static void httpPostRequestHandle()  
       {  
           while (true)  
           {  
               HttpListenerContext requestContext = httpPostRequest.GetContext();  
               Thread threadsub = new Thread(new ParameterizedThreadStart((requestcontext) =>  
               {  
                   HttpListenerContext request = (HttpListenerContext)requestcontext;  
  
                   //获取Post请求中的参数和值帮助类  
                   HttpListenerPostParaHelper httppost=new HttpListenerPostParaHelper (request);  
                   //获取Post过来的参数和数据  
                   List<HttpListenerPostValue> lst=httppost.GetHttpListenerPostValue();  
  
                   string userName = "";  
                   string password = "";  
                   string suffix = "";  
                   string adType = "";  
                     
                   //使用方法  
                   foreach (var key in lst)  
                   {  
                       if (key.type == 0)  
                       {  
                           string value = Encoding.UTF8.GetString(key.datas).Replace("\r\n", "");  
                           if (key.name == "username")  
                           {  
                               userName = value;  
                               Console.WriteLine(value);  
                           }  
                           if (key.name == "password")  
                           {  
                               password = value;  
                               Console.WriteLine(value);  
                           }  
                           if (key.name == "suffix")  
                           {  
                               suffix = value;  
                               Console.WriteLine(value);  
                           }  
                           if (key.name == "adtype")  
                           {  
                               adType = value;  
                               Console.WriteLine(value);  
                           }     
                       }  
                       if (key.type == 1)  
                       {  
                           string fileName = request.Request.QueryString["FileName"];  
                           if (!string.IsNullOrEmpty(fileName))  
                           {  
                               string filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyMMdd_HHmmss_ffff") + Path.GetExtension(fileName).ToLower();  
                               if (key.name == "File")  
                               {  
                                   FileStream fs = new FileStream(filePath, FileMode.Create);  
                                   fs.Write(key.datas, 0, key.datas.Length);  
                                   fs.Close();  
                                   fs.Dispose();  
                               }  
                           }  
                       }  
                   }  
  
                   //Response  
                   request.Response.StatusCode = 200;  
                   request.Response.Headers.Add("Access-Control-Allow-Origin", "*");  
                   request.Response.ContentType = "application/json";  
                   requestContext.Response.ContentEncoding = Encoding.UTF8;  
                   byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new {success="true",msg="提交成功" }));  
                   request.Response.ContentLength64 = buffer.Length;  
                   var output = request.Response.OutputStream;  
                   output.Write(buffer, 0, buffer.Length);  
                   output.Close();  
               }));  
               threadsub.Start(requestContext);  
           }  
       }
HttpListener  类一定要在程序结束时手动结束掉(有时调试时,明明程序已经停止,但是监听事件却在后台默默运行),建议把监听事件写在一个线程中,这样的话假如线程停掉,里面的监听事件也就停掉了。

特别注意,因为是新手,我就自以为需要把IIS网站开启才能监听,但是在调试的时候却一直报”占用”错误,后来才慢慢试明白!

另外,因为这次是做微信域名的验证,在微信请求时给微信相应的回复,刚开始就返回一个  true  可是微信说不行,后来整明白啦,原来需要回复的是微信绑定域名时的TXT文档中内容! 

这个大坑用了两天终于过去了

 

 

 

使用谷歌请求插件进行post请求    PostMan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!