检测远程URL是否存在的三种方法

本文用3种方法检测远程URL是否存在。

private void Page_Load(object sender, System.EventArgs e)
{

string url1 = "http://dotnet.aspx.cc/ ";
string url2 = " http://dotnet.aspx.cc/Images/logo.gif ";
Response.Write("

 1<li>方法1:");   
 2Response.Write(url1 + " 存在:" + UrlExistsUsingHttpWebRequest(url1).ToString());   
 3Response.Write("<li>方法2:");   
 4Response.Write(url1 + " 存在:" + UrlExistsUsingSockets(url1).ToString());   
 5Response.Write("<li>方法3:");   
 6Response.Write(url1 + " 存在:" + UrlExistsUsingXmlHttp(url1).ToString()); 
 7
 8Response.Write("<li>方法1:");   
 9Response.Write(url2 + " 存在:" + UrlExistsUsingHttpWebRequest(url2).ToString());   
10Response.Write("<li>方法3:");   
11Response.Write(url2 + " 存在:" + UrlExistsUsingXmlHttp(url2).ToString());   
12}   
13private bool UrlExistsUsingHttpWebRequest(string url)   
14{   
15try   
16{   
17System.Net.HttpWebRequest myRequest =(System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);   
18myRequest.Method = "HEAD";   
19myRequest.Timeout = 100;   
20System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)myRequest.GetResponse();   
21return (res.StatusCode == System.Net.HttpStatusCode.OK);   
22}   
23catch(System.Net.WebException we)   
24{   
25System.Diagnostics.Trace.Write(we.Message);   
26return false;   
27}   
28}   
29private bool UrlExistsUsingXmlHttp(string url)   
30{   
31//注意:此方法需要引用Msxml2.dll   
32MSXML2.XMLHTTP _xmlhttp = new MSXML2.XMLHTTPClass();   
33_xmlhttp.open("HEAD",url,false,null,null);   
34_xmlhttp.send("");   
35return (_xmlhttp.status == 200 );   
36} 
37
38private bool UrlExistsUsingSockets(string url)   
39{   
40if(url.StartsWith("http://")) url = url.Remove(0," http://".Length );   
41try   
42{   
43System.Net.IPHostEntry ipHost = System.Net.Dns.Resolve(url);   
44return true;   
45}   
46catch (System.Net.Sockets.SocketException se)   
47{   
48System.Diagnostics.Trace.Write(se.Message);   
49return false;   
50}   
51}</li></li></li></li></li>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus