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
。
如何获得第二种情况的输出?
答案 0 :(得分: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;
}
答案 1 :(得分:0)
Dns.GetHostEntry正在寻找域名,而不是网址。尝试将字符串转换为URI并首先使用URI.DnsSafeHost
string url = "http://www.google.com";
Uri uri = new Uri(url);
string domain = uri.DnsSafeHost;
答案 2 :(得分:0)
使用this
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();
}