asp.net下检测远程URL是否存在的三种方法
程序员文章站
2024-03-09 10:51:53
复制代码 代码如下:private void page_load(object sender, system.eventargs e) { string url1 = "h...
复制代码 代码如下:
private void page_load(object sender, system.eventargs e)
{
string url1 = "http://s.jb51.net/";
string url2 = "//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;
}
}
上一篇: Java异常分类及统一处理详解