Download file over HTTPS using .NET (dotnet)

后端 未结 3 1757
后悔当初
后悔当初 2021-01-16 00:41

I would like to download a file using VB.NET (preferably) or C# via HTTPS.

I have this code to download a file over plain HTTP:

Dim client As WebClie         


        
相关标签:
3条回答
  • 2021-01-16 01:11

    You just need to point that address to your HTTPS resource and to inform your credential:

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

    You're talking about how to log into a site protected by a HTML form login. I wrote this code sometime ago and you could to adapt it to login into your remote site: Orkut Login Code

    Things you need to keep in mind:

    • If that's an ASP.NET site, you need to call it first to get __EVENTTARGET and __EVENTARGUMENT values, as they're required to process your login postback. If it's not, skip this step.
    • You need to identify that names that site uses to fill your username and password
    • You must to add a CookieContainer. It keeps your login cookie, so subsequent calls uses that authenticated context.
    • After all that, you should be able to get your remote resource and to download it
    0 讨论(0)
  • 2021-01-16 01:24

    You need to add a certificate validator:

    // 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;
        }
    

    In 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
    
    0 讨论(0)
  • 2021-01-16 01:30

    Try something like this

            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);
    
    0 讨论(0)
提交回复
热议问题