此代码适用.NET 5.0 and .NET Core
此示例通过**WebProxy**进行代理设置,并通过**HttpWebResquest**发送请求。
代码
下面的代码需要用到命名空间 **System.Net**、**System.Text**、**System.IO**,请先引入命名空间
此代码以http和https代理为例
using System;
using System.Net;
using System.Text;
using System.IO;
namespace proxy_demo
{
class Program
{
 static void Main(string[] args)
 {
 sendRequest("https://www.fwvps.com", SetProxy());
 }
 private static void sendRequest(String urlStr, WebProxy proxyObj)
 {
 try
 {
 // 设置Http/https请求
 HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(urlStr);
 httpRequest.Method = "GET";
 httpRequest.Credentials = CredentialCache.DefaultCredentials;
 // 在发起HTTP请求前将proxyObj赋值给HttpWebRequest的Proxy属性
 httpRequest.Proxy = proxyObj;
 // 抓取响应返回的页面数据
 HttpWebResponse res = (HttpWebResponse)httpRequest.GetResponse();
 StreamReader reader = new StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8);
 string content = reader.ReadToEnd();
 reader.Close();
 Console.WriteLine("{0}", content);
 }
 catch (Exception e)
 {
 Console.WriteLine(e.ToString());
 }
 }
 private static WebProxy SetProxy()
 {
 WebProxy proxy = new WebProxy();
 try
 {
 // 设置代理属性WebProxy
 string server = @"tunnel.www.fwvps.com:11883"; //代理IP的服务器地址
 string proxyUser = @"4B2AF3A6"; //帐号
 string proxyPass = @"D95133B9A167"; //密码
 proxy.Address = new Uri(string.Format("http://{0}/",server));
 proxy.Credentials = new System.Net.NetworkCredential(proxyUser, proxyPass); //如使用白名单方式连接,可注释此行
 Console.WriteLine("代理服务器连接成功:{0}", server);
 return proxy;
 }
 catch (NullReferenceException e)
 {
 Console.WriteLine("代理服务器连接失败,请检查服务器地址、用户名、密码是否有误。" e.ToString());
 }
 return proxy;
 }
}
}
运行结果:
