检查URL是否正在工作或未使用

本文关键字:工作 未使用 URL 是否 检查 | 更新日期: 2023-09-27 18:03:55

string url = "www.google.com";
public bool UrlIsValid(string url)
{
    bool br = false;
    try
    {
                    IPHostEntry ipHost =  Dns.GetHostEntry(url);
                                     br = true;
    }
    catch (SocketException)
    {
        br = false;
    }
    return br;
}

上面的程序将输出true,但是当我将字符串更改为

string url = "https://www.google.com";

我得到的输出是false

我如何得到第二个case的输出?

检查URL是否正在工作或未使用

您可以尝试使用Uri类来解析url字符串。

public bool UrlIsValid(string url) {
   return UrlIsValid(new Uri(url));
}

public bool UrlIsValid(Uri url)
{
    bool br = false;
    try
    {
         IPHostEntry ipHost =  Dns.GetHostEntry(url.DnsSafeHost);
         br = true;
    }
    catch (SocketException)
    {
        br = false;
    }
    return br;
}

Dns。GetHostEntry正在寻找域名,而不是url。尝试将字符串转换为URI并使用URI。DnsSafeHost第一

string url = "http://www.google.com";
Uri uri = new Uri(url);
string domain = uri.DnsSafeHost;

使用

Uri siteUri = new Uri("http://www.contoso.com/");
WebRequest wr = WebRequest.Create(siteUri);
// now, request the URL from the server, to check it is valid and works
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse ())
{
    if (response.StatusCode == HttpStatusCode.OK)
    {
    }
    response.Close();
}