如何监听Web浏览器请求发送到服务器?

时间:2014-08-12 09:48:08

标签: c# .net http

我想在我的程序中听取Web浏览器请求将其发送到服务器,然后再打开 服务器,响应此请求。但在我的客户端代码中,无法发送request.after listener.start()我在异常中有这条消息:"参数不正确"

' try
    {

       // IPHostEntry ipHostInfo = Dns.Resolve("192.168.1.2");//GetHostAddresses(string "127.0.0.1");//Resolve("host.contoso.com");
     //   IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.BeginConnect(remoteEP,new AsyncCallback(ConnectCallback), client);
        connectDone.WaitOne();
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://127.0.0.1: 2000/");

        listener.Start();
        Console.WriteLine("im listening...");
        HttpListenerContext context = listener.GetContext();
        HttpListenerRequest requst= context.Request;

        Send(client,requst.ToString());
        sendDone.WaitOne();`

1 个答案:

答案 0 :(得分:0)

前一段时间我为此写了一个函数:

public string request(string url)
    {
        string responseText = "";
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        WebHeaderCollection header = response.Headers;

        var encoding = ASCIIEncoding.ASCII;
        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
        {
            responseText = reader.ReadToEnd();
        }

        return responseText;
    }

它不是对您的代码的更正,但可能对您有用。只需将http://127.0.0.1: 2000/作为参数,希望您已完成。