tags:

views:

2536

answers:

3

I'm writing a program that reads content from a user provided URL. My problem is in the code that goes something like this:

Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse webResponse = webRequest.GetResponse();
ReadFrom(webResponse.GetResponseStream());

And this is breaking if the provided url is an "https://" URL. Can anyone help me with changing this code so that it will work with SSL encrypted content. Thanks.

+1  A: 

Hi,

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

dotnetdev
A: 

You'll need to tell us how it breaks!

Tor Haugen
+4  A: 

You're doing it the correct way but users may be providing urls to sites that have invalid ssl certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}
LukeDuff
This was my problem exactly. I was doing it correctly except that when I was testing my code I was providing https://localhost that resulted in an error because the certificate was for www.mycompany.com. Thank you for pointing me in the right direction.
Alfred B. Thordarson