|
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是否存在的三種方法,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。