[英]I want to check whether the file in a url entered exists or not using .net
我正在开发一种工具,用于验证输入的URL中的链接。 假设我已经在textbox1中输入了网址(例如http://www-review-k6.thinkcentral.com/content/hsp/science/hspscience/na/gr3/se_9780153722271_/content/nlsg3_006.html ),并且我想检查是否所有链接的内容是否存在于远程服务器上。 最后,我想要一个损坏链接的日志文件。
您可以使用HttpWebRequest 。
注意四件事
1)如果链接不存在,则webRequest将引发异常
2)您可能想禁用自动重定向
3)您可能还想检查它是否是有效的网址。 如果不是,它将抛出UriFormatException。
更新
4)Per Paige建议,在request.Method中使用“ Head”,以免下载整个远程文件
static bool UrlExists(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "HEAD";
request.AllowAutoRedirect = false;
request.GetResponse();
}
catch (UriFormatException)
{
// Invalid Url
return false;
}
catch (WebException ex)
{
// Valid Url but not exists
HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
}
return true;
}
使用HttpWebResponse类:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.gooogle.com/");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
if (response.StatusCode == HttpStatusCode.NotFound)
{
// do something
}
bool LinkExist(string link)
{
HttpWebRequest webRequest = (HttpWebRequest) webRequest.Create(link);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
return !(webResponse.StatusCode != HttpStatusCode.NotFound);
}
向URL发出HTTP请求,看看是否收到404响应。 如果是这样,那么它不存在。
您需要一个代码示例吗?
如果您的目标是可靠地验证页面源代码,请考虑使用已编写的工具,例如W3C Link Checker 。 它可以作为命令行程序运行,以处理查找链接,图片,css等并检查其有效性。 它还可以递归检查整个网站。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.