HttpWebRequest.RequestURI.Scheme始终返回'https'

时间:2017-03-15 14:25:01

标签: c# httpwebrequest

Uncaught TypeError: arr.contains is not a function

我正在测试网址,看看它们是http还是https。我的想法是使用HttpWebRequest检查https请求是否通过,如果失败则转到http。我的问题是,如果我在浏览器中 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; } } 无法连接,但我的程序中的Web请求返回https。任何人都有更好的方法来做到这一点?

2 个答案:

答案 0 :(得分:1)

您的问题是,您没有发出请求,只是创建和实例来执行请求。

所以你真正需要做的是:

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

第二次发布也可以完成,但我认为您打算检查网站是否有https,这会产生误导。

但请记住,如果没有互联网连接,它将返回http

答案 1 :(得分:0)

添加Request.GetResponse以真正检查您是否有来自网址的响应:

var rt=request.GetResponse();

要确定,在此之后您可以检查端口

rt.ResponseUri.Port

如果返回80则必须为Http,对于https为443