C# 监听http请求

直接上代码:

  public partial class FrmHome : Form
    {

        
        HttpListener verifyHttplisten;
        private object listenLocker = new object();
        Thread ThrednHttpPostRequest;


        public FrmHome()
        {
            InitializeComponent();
        }

        private void FrmHome_Load(object sender, EventArgs e)
        {
            try
            {
                //启动HTTP监听
                verifyHttplisten = new HttpListener();
                verifyHttplisten.Prefixes.Add("http://192.168.1.199/");
                verifyHttplisten.Start();
                ThrednHttpPostRequest = new Thread(new ThreadStart(httpPostRequestHandle));
                ThrednHttpPostRequest.IsBackground = true;
                ThrednHttpPostRequest.Start();
            }
            catch(Exception ex)
            {
                //LogHelper.CreateErrorLogTxt("FrmHome_Load",ex.Source,ex.Message);
            }
        }
        
       
        /// 
        /// 等待请求的线程函数
        /// 
        private void httpPostRequestHandle()
        {
            while (true)
            {
                try
                {
                    //等待请求连接,没有请求则GetContext处于阻塞状态
                    HttpListenerContext requestContext = verifyHttplisten.GetContext();
                    Thread m_threadsub = new Thread(new ParameterizedThreadStart((requestcontext) =>
                    {
                        try
                        {
                            lock (listenLocker)
                            {
                                ResponseEntity result = new ResponseEntity();
                                RequstEntity requstEntity = new RequstEntity();
                                //客户端发送过来的信息
                                HttpListenerContext request = (HttpListenerContext)requestcontext;
                                //获取HTTPRequest的帮助类
                                HttpListenerHelper httppost = new HttpListenerHelper(request);
                                //获取HTTPRequestbody,RequstEntity定义的一个类,用来接收解析接收到的json数据
                                requstEntity = httppost.GetHttpListenerPostValue();

                                switch (request.Request.HttpMethod)
                                {
                                    case "POST":
                                        if (request.Request.RawUrl == "/api/v1/Face/FaceSearch")
                                        {
                                            //这里写接收到请求的处理函数
                                        }
                                        break;
                                    case "PUT":
                                        if (request.Request.RawUrl == "/api/v1/Face/FaceAdd")
                                        {
                                             //这里写接收到请求的处理函数
                                        }
                                        break;
                                    case "GET":
                                        if (request.Request.RawUrl == "/api/v1/Face/GetCount")
                                        {
                                            //这里写接收到请求的处理函数
                                        }
                                        break;
                                    case "DELETE":
                                        Regex urlMach = new Regex("/api/v1/Face/FaceDel");
                                        if (urlMach.IsMatch(request.Request.RawUrl))
                                        {
                                             //这里写接收到请求的处理函数
                                        }
                                        break;
                                }

                                //Response  
                                request.Response.StatusCode = 200;
                                request.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                                request.Response.ContentType = "application/json";
                                request.Response.ContentEncoding = Encoding.UTF8;
                                byte[] buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
                                request.Response.ContentLength64 = buffer.Length;
                                var output = request.Response.OutputStream;
                                output.Write(buffer, 0, buffer.Length);
                                output.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            //LogHelper.CreateErrorLogTxt("verifyhttplistern", ex.Source.ToString(), ex.Message);
                        }
                    }));
                    m_threadsub.IsBackground = true;
                    m_threadsub.Start(requestContext);
                }
                catch (Exception ex)
                {
                    //LogHelper.CreateErrorLogTxt("httpRequestHandle", ex.Source, ex.Message);
                }
            }
        }
    }
}

解析http请求Request Body:

namespace Falcon.Utils
{
    

    ///   
    /// 获取http请求中的参数和值帮助类  
    ///   
    public class HttpListenerHelper
    {
        private HttpListenerContext request;

        public HttpListenerHelper(HttpListenerContext request)
        {
            this.request = request;
        }

        

        
        /// 
        /// 获取httprequestbody过来的参数和数据 
        /// 
        /// 
        /// 
        public T GetHttpListenerPostValue()
        {
            try
            {
                T response= default(T);
                if (request.Request.ContentType.StartsWith("application/json"))
                {
                    using (Stream inputStream = request.Request.InputStream)
                    {
                        using (StreamReader reader = new StreamReader(inputStream))
                        {
                            string json = reader.ReadToEnd();
                            response = JsonConvert.DeserializeObject(json);
                        }
                    }
                }
                return response;
            }
            catch(Exception ex)
            {
               // LogHelper.CreateErrorLogTxt("GetHttpListenerPostValue", ex.Source.ToString(), ex.Message);
                return default(T);
            }
        }
   }
}

 

你可能感兴趣的:(C#)