HttpWebRequest代理访问网站

时间:2021-12-04 14:58:42
private void button1_Click(object sender, EventArgs e)
{
string str ="http://www.7y8.com/V/ip.asp";
MessageBox.Show("访问的IP地址是:"+getIPAddr(GetResponseStr(str)));
} //使用代理访问
private string GetResponseStr(string str)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(str);
request.Proxy = CreatProxy("http://65.110.17.142:80","","");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();//获得回应的数据流
//将数据流转成 String
string result = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
return result;
} /// <summary>
/// 创建代理对象
/// </summary>
/// <param name="str_IP">HTTP代理地址(默认是80端口)</param>
/// <param name="str_UserName">用户名(匿名则用户名和密码为空)</param>
/// <param name="str_Pwd">密码</param>
/// <returns></returns>
private WebProxy CreatProxy(string str_IP, string str_UserName, string str_Pwd)
{
str_IP = str_IP.ToUpper().IndexOf("HTTP://") > -1 ? str_IP : "http://" + str_IP;
WebProxy myProxy = new WebProxy();
myProxy.Address = new Uri(str_IP);
myProxy.Credentials = new NetworkCredential(str_UserName, str_Pwd);
return myProxy;
} //抓取页面上显示的IP地址
private string getIPAddr(string str)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
return reg.Match(str).Value.ToString();
}