HttpWebRequest.RequestURI.Scheme Always Return 'https'


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

我正在测试URL,以查看它们是HTTP还是HTTP。我的想法是使用httpwebrequest检查HTTPS请求是否通过,并且是否失败了HTTP。我的问题是,如果我在浏览器中使用https://business.lynchburgchamber.org,如果无法连接,则我的Web请求会返回HTTPS。任何人都有更好的方法?

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

所以您实际要做的就是这样:

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,这将是误导的。

,请记住,如果没有Internet连接,它将返回http

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

var rt=request.GetResponse();

为了真正确定,此后您可以检查端口

rt.ResponseUri.Port

如果它返回80,则必须是http,443对于https

相关内容

  • 没有找到相关文章

最新更新