22 November 2017

Download file over HTTPS using Net.WebClient / Scaricare un file via HTTPS con Net.WebClient

Using Net.WebClient over HTTPS returns this error:
The underlying connection was closed: An unexpected error occurred on a send.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

You have to setup a ServerCertificateValidationCallback event and set the right SecurityProtocol:
Imports System.Net
Imports System.Net.Security
Imports System.Security.Cryptography.X509Certificates

Public Class HTTPS_Test

    Private Function validateCertificate(sender As Object,
                                         certificate As X509Certificate,
                                         chain As X509Chain,
                                         sslPolicyErrors As SslPolicyErrors
                                         ) As Boolean

        '' If the certificate is a valid, signed certificate, return true.
        'If sslPolicyErrors = Security.SslPolicyErrors.None Then
        '    Return True
        'Else
        '    Console.WriteLine("X509Certificate [{0}] Policy Error: '{1}'",
        '                      certificate.Subject,
        '                      sslPolicyErrors.ToString)
        '    Return False
        'End If

        Return True

    End Function


    Public Sub DownloadFromHTTPS()


        '-- IMPOSTAZIONI PER USARE HTTPS/CERTIFICATI - da impostare prima di usare il WebClient
        ServicePointManager.ServerCertificateValidationCallback = AddressOf validateCertificate

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 Or
                                                    SecurityProtocolType.Tls Or
                                                    SecurityProtocolType.Tls11 Or
                                                    SecurityProtocolType.Tls12



        Dim url As String = "https://..."

        Using myWebClient As New WebClient()
            Dim data As String = myWebClient.DownloadString(url)
        End Using

    End Sub

End Class


Docs:
  1. Download file over HTTPS using .Net
  2. Set the SecurityProtocol Ssl3 or Tls on the Net.
  3. Best practices for using ServerCertificateValidationCallback