0
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.

如何获得第二种情况的输出?

4

3 回答 3

2

您可以尝试使用 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;
}
于 2013-03-14T09:22:58.530 回答
0

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

string url = "http://www.google.com";
Uri uri = new Uri(url);
string domain = uri.DnsSafeHost;
于 2013-03-14T09:22:50.377 回答
0

使用这个

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();
}
于 2013-03-14T09:29:43.627 回答