天天看點

c#中HttpWebRequest使用Proxy實作指定IP的域名請求

我有這麼一個需求:

一個域名,xxx.com,它後面其實有很多個iP:比如:
           

1.2.3.4,

5.6.7.8,

9.10.11.12

這些ip上面都有同樣的網站,域名解析的時候會随機配置設定一個ip給你(這個就是DNS負載均衡)。

但是現在假如我想通路一個特定IP的上的網站,比如5.6.7.8上的網站,但是由于網站限制了必須通過域名才能通路,直接把域名改成ip位址形成的url如:

http://5.6.7.8/

,這樣子是不行的。

怎麼辦呢?

有兩種方法:

  1. 修改Hosts檔案,指定xxx.com 解析到5.6.7.8 上面去。
  2. 使用 這個url,不過在請求包的head頭裡增加一句:

Host:xxx.com

由于我是通過C#代碼來實作這個功能,是以就想通過第2種方法解決。

C#中是用HttpWebRequest類來實作擷取一個http請求的。它有一個Header的屬性,可以修改Header裡頭的值。不過查詢MSDN得知,這個Host辨別是沒辦法通過這種方法修改的。如果你這麼使用:

httpWebRequest.Headers["Host"] =”xxx.com”;

它會抛出一個異常出來:

ArgumentException: The 'Host' header cannot be modified directly。

那還能不能實作上面的需求呢?答案是能,不過方法要改一下:

Url裡面還是使用域名:

http://xxx.com/

設定HttpWebRequest的Proxy屬性為你想通路的IP位址即可,如下:

httpWebRequest.Proxy = new WebProxy(ip.ToString());

參考代碼如下(代碼來自參考資料一):

using System;

using System.IO;

using System.Net;

namespace ConsoleApplication1

{

class Program
{
    public static void Main(string[] args)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com/Default.aspx");
        System.Net.WebProxy proxy = new WebProxy("208.77.186.166", 80);
        request.Proxy = proxy;
        using (WebResponse response = request.GetResponse())
        {
            using (TextReader reader = new StreamReader(response.GetResponseStream()))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                    Console.WriteLine(line);
            }
        }
    }
}           

}

這樣子就實作了指定IP的域名請求。

附:有人已經向微軟回報了無法修改host頭的問題,微軟回報說下一個.Net Framewok中将增加一個新的Host屬性,這樣子就可以修改Host頭了。

原文:

由 Microsoft 在 2009/5/26 13:37 發送

The next release of the .NET Framework will include a new "Host" property. The value of this property will be sent as "Host" header in the HTTP request.

參考資料:

HttpWebRequest.Headers["Host"] throws an unexpected exception