通过代理获取html源代码

时间:2012-07-20 08:06:36

标签: c# vb.net

您如何通过代理获取html页面的来源。当我使用下面的代码时,我收到一条错误消息“需要代理身份验证”。我必须通过代理。

Dim client As New WebClient()

Dim htmlCode As String = client.DownloadString("http://www.stackoverflow.com")

1 个答案:

答案 0 :(得分:3)

然后使用不需要身份验证的代理

请点击此处了解更多信息 http://msdn.microsoft.com/en-us/library/system.net.webclient.proxy.aspx

string source = GetPageSource("http://www.stackoverflow.com");

    private string GetPageSource(string url)
    {
        string htmlSource = string.Empty;
        try
        {
            System.Net.WebProxy myProxy = new System.Net.WebProxy("Proxy IP", 8080);
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Proxy = myProxy;
                client.Proxy.Credentials = new System.Net.NetworkCredential("username", "password");
                htmlSource = client.DownloadString(url);
            }
        }
        catch (WebException ex)
        { 
            // log any exceptions
        }
        return htmlSource;
    }