我需要创建一个发送到我们网站的网页请求,但我也需要能够设置主机头信息.我已经尝试使用HttpWebRequest,但Header信息是只读的(至少它的主机部分是).我需要这样做,因为我们想在用户可以之前执行页面的初始请求.我们有10个负载均衡的Web服务器,因此我们需要从每个Web服务器请求该文件.
我尝试过以下方法:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.1.5/filename.htm"); request.Headers.Set("Host", "www.mywebsite.com"); WebResponse response = request.GetResponse();
显然这不起作用,因为我无法更新标题,我不知道这是否确实是正确的方法.
虽然这是一个非常晚的答案,也许有人可以从中获益
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://192.168.1.1")); request.Headers.GetType().InvokeMember("ChangeInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, request.Headers, new object[] {"Host","www.mysite.com"});
反思是你的朋友:)
我已经设法通过使用套接字找到更长的绕线路线.我在IPEndPoint的MSDN页面中找到了答案:
string getString = "GET /path/mypage.htm HTTP/1.1\r\nHost: www.mysite.mobi\r\nConnection: Close\r\n\r\n"; Encoding ASCII = Encoding.ASCII; Byte[] byteGetString = ASCII.GetBytes(getString); Byte[] receiveByte = new Byte[256]; Socket socket = null; String strPage = null; try { IPEndPoint ip = new IPEndPoint(IPAddress.Parse("10.23.1.93"), 80); socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(ip); } catch (SocketException ex) { Console.WriteLine("Source:" + ex.Source); Console.WriteLine("Message:" + ex.Message); } socket.Send(byteGetString, byteGetString.Length, 0); Int32 bytes = socket.Receive(receiveByte, receiveByte.Length, 0); strPage = strPage + ASCII.GetString(receiveByte, 0, bytes); while (bytes > 0) { bytes = socket.Receive(receiveByte, receiveByte.Length, 0); strPage = strPage + ASCII.GetString(receiveByte, 0, bytes); } socket.Close();