使用.NET(dotnet)通过HTTPS下载文件

时间:2010-01-26 12:19:43

标签: vb.net file https download

我想使用VB.NET(最好)或C#通过HTTPS下载文件。

我有这个代码通过普通的HTTP下载文件:

Dim client As WebClient = New WebClient()
Dim wp As WebProxy = New WebProxy("[IP number of our proxy server]", [port number of our proxy server])
wp.Credentials = CredentialCache.DefaultCredentials
client.Proxy = wp
client.DownloadFile("http://sstatic.net/so/img/logo.png", "c:\logo.png")

这很有效。

如何更改此代码以下载存储在HTTPS服务器上的文件?我想这与添加凭据或其他东西有关。

3 个答案:

答案 0 :(得分:2)

<击> 您只需将该地址指向您的HTTPS资源并通知您的凭证:

client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile("https://your.resource.here", @"localfile.jog")

<击>

您正在谈论如何登录受HTML表单登录保护的站点。我之前写过这段代码,你可以调整它来登录你的远程站点:Orkut Login Code

您需要牢记的事情:

  • 如果这是一个ASP.NET站点,您需要先调用它来获取__EVENTTARGET__EVENTARGUMENT值,因为它们需要处理您的登录回发。如果不是,请跳过此步骤。
  • 您需要确定网站用来填充用户名和密码的名称
  • 您必须添加CookieContainer。它会保留您的登录cookie,以便后续调用使用该经过身份验证的上下文。
  • 毕竟,您应该能够获取远程资源并下载它

答案 1 :(得分:1)

您需要添加证书验证程序:

// You need to call it only once in a static constructor or multiple times there is no problem
ServicePointManager.ServerCertificateValidationCallback = ValidateCertificate;

    private static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }

在VB中:

ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateCertificate
Dim client As WebClient = New WebClient()
'...
'Your code

  Private Shared Function ValidateCertificate(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) As Boolean
        return True
  End Function

答案 2 :(得分:0)

尝试这样的事情

        WebClient wc = new WebClient();
        wc.UseDefaultCredentials = false;

        CredentialCache creds = new CredentialCache();
        creds.Add(new Uri(url), "Basic",new NetworkCredential(username, password, domain));

        wc.Credentials = creds;
        wc.Headers.Add(HttpRequestHeader.UserAgent,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;");
        //wc.Headers["Accept"] = "/";

        wc.DownloadFile(url,localpath);