简体   繁体   English

如何将远程代理添加到所有WebClient请求

[英]How to add remote proxy to all WebClient requests

This is my code, what is the best way to make sure that these requests are passed over remote proxy? 这是我的代码,确保这些请求通过远程代理传递的最佳方法是什么?

        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);

I think your code is wrong... 我觉得你的代码错了......
here is working one: 这是工作一个:

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;

As a method to make shure that these requests are passed over remote proxy to use smth like myip.net 作为一种方法来使这些请求通过远程代理传递以使用像myip.net这样的smth

        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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM