2010-01-26 70 views
0

我想通过HTTPS使用VB.NET(最好)或C#下载文件。使用.NET(dotnet)通过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服务器上的文件?我想这与添加凭证或某事有关。

+0

只需在DownloadFile函数中用'https'替换'http'即可。 – 2010-01-26 12:30:23

+0

不,然后我得到以下错误:“远程服务器返回错误:(403)禁止。”我应该能够给出用户名和密码。 – George 2010-01-26 12:51:04

+0

嗨...刚刚从谷歌登陆这里,实际上没有看到这个问题,但立即发现了一个可能的问题在你的代码中:“c:\ logo.png”,\ l是一个转义序列(无效?),除非它有一个@之前或它是“c:\\ logo.png” – 2010-09-09 17:17:45

回答

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,以便后续的调用使用该认证的上下文。
  • 毕竟,你应该能够得到您的远程资源和下载
+0

不,然后我得到以下错误:“远程服务器返回错误:(403)禁止。”我应该能够给出用户名和密码。 – George 2010-01-26 12:23:29

+0

嗯,你如何在该网站登录?它是一个窗口对话框,还是你有一个HTML表单来填充? – 2010-01-26 12:24:32

+0

有一个HTML表格可以填写。 – George 2010-01-26 12:25:49

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 
+1

IIRC你应该只需要这样做,如果SSL证书不是100%好 – 2010-01-26 12:43:22

+0

但是代码在哪里提交我们的用户名和密码? – George 2010-01-26 12:55:45

+0

@Marc:当然,我曾经认为问题在于iar :) – MarcosMeli 2010-01-26 13:19:58

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