asp.net下检测远程URL是否存在的三种方法

复制代码 代码如下:
private void Page_Load(object sender, System.EventArgs e)
{
string url1 = "http://s.jb51.NET/";
string url2 = "http://www.jb51.NET/images/logo.gif";
Response.Write("<li>方法1:");
Response.Write(url1 + " 存在:" + UrlExistsUsingHttpWebRequest(url1).ToString());
Response.Write("<li>方法2:");
Response.Write(url1 + " 存在:" + UrlExistsUsingSockets(url1).ToString());
Response.Write("<li>方法3:");
Response.Write(url1 + " 存在:" + UrlExistsUsingXmlHttp(url1).ToString());
Response.Write("<li>方法1:");
Response.Write(url2 + " 存在:" + UrlExistsUsingHttpWebRequest(url2).ToString());
Response.Write("<li>方法3:");
Response.Write(url2 + " 存在:" + UrlExistsUsingXmlHttp(url2).ToString());
}

private bool UrlExistsUsingHttpWebRequest(string url){
try
{
System.NET.HttpWebRequest myRequest = (System.NET.HttpWebRequest)System.NET.WebRequest.Create(url);
myRequest.Method = "HEAD";
myRequest.Timeout = 100;
System.NET.HttpWebResponse res = (System.NET.HttpWebResponse)myRequest.GetResponse();
return (res.StatusCode == System.NET.HttpStatusCode.OK);
}
catch (System.NET.WebException we)
{
System.Diagnostics.Trace.Write(we.Message);
return false;
}
}

private bool UrlExistsUsingXmlHttp(string url)
{
//注意:此方法需要引用Msxml2.dll
MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();
_xmlhttp.open("HEAD", url, false, null, null);
_xmlhttp.send("");
return (_xmlhttp.status == 200);
}
private bool UrlExistsUsingSockets(string url)
{
if (url.StartsWith("http://")) url = url.Remove(0, "http://".Length);
try
{
System.NET.IPHostEntry ipHost = System.NET.Dns.Resolve(url);
return true;
}
catch (System.NET.Sockets.SocketException se)
{
System.Diagnostics.Trace.Write(se.Message);
return false;
}
}

AspNet技术asp.net下检测远程URL是否存在的三种方法,转载需保留来源!

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。