如何将远程代理添加到所有 Web 客户端请求

本文关键字:添加 Web 请求 客户端 代理 程代理 | 更新日期: 2023-09-27 18:33:30

这是我的代码,确保这些请求通过远程代理传递的最佳方法是什么?

        String openUrl = @"www.site.com/page.html";
        WebClient myClient = new WebClient();
        myClient.UseDefaultCredentials = true;
        IWebProxy theProxy = myClient.Proxy;
        if (theProxy != null)
        {
            theProxy.Credentials = CredentialCache.DefaultCredentials;
        }
        myClient.Proxy = WebRequest.DefaultWebProxy;
        string webPageString = myClient.DownloadString(openUrl);
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(webPageString);

如何将远程代理添加到所有 Web 客户端请求

我认为你的代码是错误的...
这是工作之一:

WebProxy p = null;
string proxyAddressAndPort ="I.P.ADD.RES:port";
string proxyUserName ="%username%";
string proxyPassword ="%password%";
ICredentials cred;
cred = new NetworkCredential(proxyUserName, proxyPassword);
p = new WebProxy(proxyAddressAndPort, true, null, cred);
WebRequest.DefaultWebProxy = p;

作为一种使这些请求通过远程代理传递以使用 smth 的方法 myip.net

        HtmlWeb hw = new HtmlWeb();
        hw.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
        hw.PreRequest = new HtmlAgilityPack.HtmlWeb.PreRequestHandler(p.ProxyOnPreRequest); // this is proxy request
        HtmlAgilityPack.HtmlDocument doc = hw.Load(openUrl);
    public bool ProxyOnPreRequest(HttpWebRequest request)
    {
        WebProxy myProxy = new WebProxy("203.189.134.17:80");
        request.Proxy = myProxy;
        return true; // ok, go on
    }