5

I have a https URL which throws below exception:

Exception Details: System.Exception: The underlying connection was closed: An unexpected error occurred on a send. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream.

I tried using the HTTP version of URL and that is working. I also checked if https URLs are accessible from machine and they are accessible without any error, but failing in below code. Also this problem is machine specific.

Line of code throwing error:

 using (WebDownloadClient wc = new WebDownloadClient())
 {
     wc.Headers.Add("Content-Encoding", "gzip");
     wc.Headers.Add("Accept-Encoding", "gzip, compress");
     wc.DownloadFile(url, fileName);
 }
Pritam
  • 1,288
  • 5
  • 23
  • 40

1 Answers1

2
    ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 ;

    using (WebDownloadClient wc = new WebDownloadClient())
    {
        wc.Headers.Add("Content-Encoding", "gzip");
        wc.Headers.Add("Accept-Encoding", "gzip, compress");
        wc.DownloadFile(url, fileName);
    }

private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
    if (error == System.Net.Security.SslPolicyErrors.None)
    {
        return true;
    }
    return false;
}

Taken from Requesting html over https with c# Webclient

Community
  • 1
  • 1
  • I cam across a below line in code. Does this enforce to use valid cert only? ServicePointManager.CertificatePolicy = new CertificatePolicy(); – Pritam Aug 24 '15 at 04:11
  • When the CertificatePolicy property is set to an ICertificatePolicy interface object, the ServicePointManager object uses the certificate policy defined in that instance instead of the default certificate policy. The default certificate policy allows valid certificates and valid certificates that have expired. –  Aug 24 '15 at 11:30
  • Thanks @HyunMi. Also I observed on m/c I could access https URL in browser but through code I getting above exception. – Pritam Aug 26 '15 at 03:06