Three ways to detect the existence of a remote URL under asp.net-practical tips

Source: Internet
Author: User
Copy Code code as follows:

private void Page_Load (object sender, System.EventArgs e)
{
String url1 = "http://s.jb51.net/";
String url2 = "Yun_qi_img/logo.gif";
Response.Write ("<li> Method 1:");
Response.Write (URL1 + "presence:" + urlexistsusinghttpwebrequest (URL1). ToString ());
Response.Write ("<li> Method 2:");
Response.Write (URL1 + "presence:" + urlexistsusingsockets (URL1). ToString ());
Response.Write ("<li> Method 3:");
Response.Write (URL1 + "presence:" + urlexistsusingxmlhttp (URL1). ToString ());
Response.Write ("<li> Method 1:");
Response.Write (Url2 + "presence:" + urlexistsusinghttpwebrequest (URL2). ToString ());
Response.Write ("<li> Method 3:");
Response.Write (Url2 + "presence:" + 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)
{
Note: This method requires reference to 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;
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.