HTTP请求转发

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MQ
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            ServicePointManager.Expect100Continue = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                HttpListener listerner = new HttpListener();
                string configAddress = GetLocalIP();
                string port = textBox1.Text.Trim();
                string url = "http://" + configAddress + ":" + port + "/";
                WriteLine("监听地址:"+url);
                try
                {
                    listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
                    listerner.Prefixes.Add(url); //指定监听端口
                    listerner.Start();
                    WriteLine("成功连接服务器.....");
                }
                catch (Exception ex)
                {
                    WriteLine("未能成功连接服务器.....");
                    listerner = new HttpListener();
                    throw ex;
                }
               
                int maxThreadNum, portThreadNum;

                //线程池
                int minThreadNum;
                ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
                ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
                WriteLine("最大线程数:{0}", maxThreadNum.ToString());
                WriteLine("最小空闲线程数:{0}", minThreadNum.ToString());


                //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);

                WriteLine("等待客户连接中。。。。");
                Thread.Sleep(1000);
                //while (true)
                //{
                    //等待请求连接
                    //没有请求则GetContext处于阻塞状态
                   
                     
                ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), listerner);
                //}
                //Thread thread = new Thread(() => TaskProc(listerner));
            }
            catch (Exception)
            {
                 
                throw;
            }
        }
        public  void TaskProc(object o)
        {
            HttpListener listerner = (HttpListener)o;
            HttpListenerContext ctx = listerner.GetContext();
            string type = ctx.Request.QueryString["type"];
            string url = ctx.Request.RawUrl;
            WriteLine("收到一个请求url=" + url);
            string requestModel = string.Empty;
            using (Stream requestStream = ctx.Request.InputStream)
            {
                using (StreamReader sr = new StreamReader(requestStream))
                {
                    requestModel = sr.ReadToEnd();
                }
            }
            int StatusCode = 200;
            var response = redirect(ctx.Request, url,ref StatusCode);
            ctx.Response.StatusCode = StatusCode;//设置返回给客服端http状态代码
            ctx.Response.ContentType = response.ContentType;
            if (response.ContentLength >= 0)
            { 
                ctx.Response.ContentLength64 = response.ContentLength;
            }
            //ctx.Response.ContentEncoding = Encoding.GetEncoding(response.ContentEncoding);
            foreach (var key in response.Headers.AllKeys)
            {
                try
                {
                    ctx.Response.Headers.Add(key, response.Headers[key]);
                }
                catch (Exception e)
                {
                    continue;
                }
            }
            response.GetResponseStream().CopyTo(ctx.Response.OutputStream);
            if (StatusCode == 200)
            {
                WriteLine("请求成功!");
            }
            TaskProc(listerner);
        }

        /// <summary>
        /// 取本机主机ip
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            try
            {

                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        string ip = "";
                        ip = IpEntry.AddressList[i].ToString();
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public  void WriteLine(string str)
        {
            if (richTextBox1.InvokeRequired)
            {
                // 当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它
                Action<string> actionDelegate = (x) => { this.richTextBox1.Text += x + "\r\n"; };
                // 或者
                // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; };
                this.richTextBox1.Invoke(actionDelegate, str);
            }
            else
            { 
            richTextBox1.Text += str + "\r\n";
            Application.DoEvents();
            }
        }
        public  void WriteLine(string str,params string[] para)
        {
            string msg = string.Format(str, para);
            WriteLine(msg);
        }

        public HttpWebResponse redirect(HttpListenerRequest request,string url,ref int StatusCode)
        {
            url = "http://cqms-sit.h3c.com" + url;
            HttpWebRequest newrequest = WebRequest.Create(url) as HttpWebRequest;
           
            newrequest.Method = request.HttpMethod;
            //newrequest.Connection = request.Headers["Connection"];
            foreach (var key in request.Headers.AllKeys)
            {
                try
                {
                    newrequest.Headers.Add(key, request.Headers[key]);
                }
                catch (Exception e)
                {
                    continue;
                }
            }
            newrequest.IfModifiedSince = DateTime.Now;
            newrequest.Date = DateTime.Now;
            newrequest.Accept = string.Join(",", request.AcceptTypes);
            newrequest.KeepAlive = request.KeepAlive;
            newrequest.ContentType = request.ContentType;
           
            if (request.Cookies != null&& request.Cookies.Count>0)
            { 
                newrequest.CookieContainer.Add(request.Cookies);
            }
            newrequest.ContentLength = request.ContentLength64;
            if (newrequest.Method.ToLower() == "post")
            { 
                using (Stream reqStream = newrequest.GetRequestStream())
                {
                    request.InputStream.CopyTo(reqStream);
                    reqStream.Close();
                }
            }
            HttpWebResponse resp;
            try
            {
                 resp = (HttpWebResponse)newrequest.GetResponse();
            }
            catch (WebException e)
            {
                resp = (HttpWebResponse)e.Response;
                WriteLine("请求相应错误:" + e.Status + ",Message:"+e.Message);
                StatusCode = 501;
            }
            //Stream stream = resp.GetResponseStream();
            ////获取响应内容
            //string result = string.Empty;
            //using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            //{
            //     result = reader.ReadToEnd();
            //}
            return resp;
        }
    }
}

 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;
namespace MQ{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();            ServicePointManager.Expect100Continue = false;        }
        private void button1_Click(object sender, EventArgs e)        {            try            {                HttpListener listerner = new HttpListener();                string configAddress = GetLocalIP();                string port = textBox1.Text.Trim();                string url = "http://" + configAddress + ":" + port + "/";                WriteLine("监听地址:"+url);                try                {                    listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问                    listerner.Prefixes.Add(url); //指定监听端口                    listerner.Start();                    WriteLine("成功连接服务器.....");                }                catch (Exception ex)                {                    WriteLine("未能成功连接服务器.....");                    listerner = new HttpListener();                    throw ex;                }                               int maxThreadNum, portThreadNum;
                //线程池                int minThreadNum;                ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);                ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);                WriteLine("最大线程数:{0}", maxThreadNum.ToString());                WriteLine("最小空闲线程数:{0}", minThreadNum.ToString());

                //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);
                WriteLine("等待客户连接中。。。。");                Thread.Sleep(1000);                //while (true)                //{                    //等待请求连接                    //没有请求则GetContext处于阻塞状态                                                        ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), listerner);                //}                //Thread thread = new Thread(() => TaskProc(listerner));            }            catch (Exception)            {                                 throw;            }        }        public  void TaskProc(object o)        {            HttpListener listerner = (HttpListener)o;            HttpListenerContext ctx = listerner.GetContext();            string type = ctx.Request.QueryString["type"];            string url = ctx.Request.RawUrl;            WriteLine("收到一个请求url=" + url);            string requestModel = string.Empty;            using (Stream requestStream = ctx.Request.InputStream)            {                using (StreamReader sr = new StreamReader(requestStream))                {                    requestModel = sr.ReadToEnd();                }            }            int StatusCode = 200;            var response = redirect(ctx.Request, url,ref StatusCode);            ctx.Response.StatusCode = StatusCode;//设置返回给客服端http状态代码            ctx.Response.ContentType = response.ContentType;            if (response.ContentLength >= 0)            {                 ctx.Response.ContentLength64 = response.ContentLength;            }            //ctx.Response.ContentEncoding = Encoding.GetEncoding(response.ContentEncoding);            foreach (var key in response.Headers.AllKeys)            {                try                {                    ctx.Response.Headers.Add(key, response.Headers[key]);                }                catch (Exception e)                {                    continue;                }            }            response.GetResponseStream().CopyTo(ctx.Response.OutputStream);            if (StatusCode == 200)            {                WriteLine("请求成功!");            }            TaskProc(listerner);        }
        /// <summary>        /// 取本机主机ip        /// </summary>        /// <returns></returns>        public static string GetLocalIP()        {            try            {
                string HostName = Dns.GetHostName(); //得到主机名                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);                for (int i = 0; i < IpEntry.AddressList.Length; i++)                {                    //从IP地址列表中筛选出IPv4类型的IP地址                    //AddressFamily.InterNetwork表示此IP为IPv4,                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)                    {                        string ip = "";                        ip = IpEntry.AddressList[i].ToString();                        return IpEntry.AddressList[i].ToString();                    }                }                return "";            }            catch (Exception ex)            {                return ex.Message;            }        }        public  void WriteLine(string str)        {            if (richTextBox1.InvokeRequired)            {                // 当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它                Action<string> actionDelegate = (x) => { this.richTextBox1.Text += x + "\r\n"; };                // 或者                // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; };                this.richTextBox1.Invoke(actionDelegate, str);            }            else            {             richTextBox1.Text += str + "\r\n";            Application.DoEvents();            }        }        public  void WriteLine(string str,params string[] para)        {            string msg = string.Format(str, para);            WriteLine(msg);        }
        public HttpWebResponse redirect(HttpListenerRequest request,string url,ref int StatusCode)        {            url = "http://cqms-sit.h3c.com" + url;            HttpWebRequest newrequest = WebRequest.Create(url) as HttpWebRequest;                       newrequest.Method = request.HttpMethod;            //newrequest.Connection = request.Headers["Connection"];            foreach (var key in request.Headers.AllKeys)            {                try                {                    newrequest.Headers.Add(key, request.Headers[key]);                }                catch (Exception e)                {                    continue;                }            }            newrequest.IfModifiedSince = DateTime.Now;            newrequest.Date = DateTime.Now;            newrequest.Accept = string.Join(",", request.AcceptTypes);            newrequest.KeepAlive = request.KeepAlive;            newrequest.ContentType = request.ContentType;                       if (request.Cookies != null&& request.Cookies.Count>0)            {                 newrequest.CookieContainer.Add(request.Cookies);            }            newrequest.ContentLength = request.ContentLength64;            if (newrequest.Method.ToLower() == "post")            {                 using (Stream reqStream = newrequest.GetRequestStream())                {                    request.InputStream.CopyTo(reqStream);                    reqStream.Close();                }            }            HttpWebResponse resp;            try            {                 resp = (HttpWebResponse)newrequest.GetResponse();            }            catch (WebException e)            {                resp = (HttpWebResponse)e.Response;                WriteLine("请求相应错误:" + e.Status + ",Message:"+e.Message);                StatusCode = 501;            }            //Stream stream = resp.GetResponseStream();            ////获取响应内容            //string result = string.Empty;            //using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))            //{            //     result = reader.ReadToEnd();            //}            return resp;        }    }}

 

HTTP请求转发

上一篇:vue.js环境的搭建


下一篇:优秀PHP程序员职业生涯技术提升心得技巧与阶梯规划方案总结