static void Main()
{
Console.WriteLine("10504: " + TestURL("business.lynchburgchamber.org"));
Console.WriteLine("Google: " + TestURL("google.com"));
Console.ReadKey();
}
static string TestURL(string baseURL)
{
try
{
string httpsURL = "https://" + baseURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpsURL);
return request.RequestUri.Scheme;
}
catch
{
string httpURL = "http://" + baseURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpURL);
return request.RequestUri.Scheme;
}
}
I am testing urls to see if they are either http or https. My idea was to use an HttpWebRequest to check if the https request goes through, and if it fails go for the http. My problem is that if I go to https://business.lynchburgchamber.org
in my browser if fails to connect, but my web request in my program returns https. Anyone have a better way to do this?
Your problem is, that you are not issuing the request, your just creating and instance to do the request.
So what you actually have to do is this:
static string TestURL(string baseURL)
{
try
{
string httpsURL = "https://" + baseURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpsURL);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return request.RequestUri.Scheme;
}
catch
{
string httpURL = "http://" + baseURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpURL);
//request.Method = "GET";
//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return request.RequestUri.Scheme;
}
}
The second issuing could be also done, but as I think you are intending to check if a site has https
, this would be misleading.
But keep in mind that it will return http
if there is no internet connection!