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. 使用http://5.6.7.8/这个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.

参考资料:

  1. HttpWebRequest.Headers["Host"] throws an unexpected exception
posted @ 2010-04-11 23:55  林杰的博客  阅读(25554)  评论(4编辑  收藏  举报