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

时间:2012-05-06 16:53:47

标签: c# winforms proxy webclient

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

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

2 个答案:

答案 0 :(得分:1)

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

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;

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

答案 1 :(得分:1)

        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
    }