是否有人知道任何好的链接验证API。我不想寻找任何类型的网络爬虫,只是为了验证整个页面或单个链接。我一直在寻找一个,因为我遇到了一些目前无法解决的地雷问题。.NET链接验证器API?
几个主要问题是:
- 一些异步Web请求上房
- 获得太多的误判
- 获得404当它是一个重定向
我会在案件中张贴我的代码。
第一种方法是开始验证
private void urlCheck(Link strUri)
{
try
{
Uri uri = new Uri(strUri.URL ,
(strUri.URL.StartsWith("/")) ?
UriKind.Relative : UriKind.Absolute);
if(!uri.IsAbsoluteUri)
uri = new Uri(_page.HttpDomain + uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.UserAgent =
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0)";
request.AllowAutoRedirect = true;
request.AllowWriteStreamBuffering = true;
request.SendChunked = true;
request.UnsafeAuthenticatedConnectionSharing = true;
request.KeepAlive = false;
request.Referer = "http://www.google.ca/";
// default : WebRequest.DefaultWebProxy
request.Proxy = null;
request.Timeout = 20000;
//do not revalidate this
WebPageCollection.DoNotRevalidateLinks.Add(strUri);
request.BeginGetResponse(new AsyncCallback(getResponseCallback) ,
request);
_webRequest++;
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
第二种方法是回调
private void getResponseCallback(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
string strUri = request.Address.ToString();
Link href = new Link(strUri);
href.URLKind = urlKind;
href.URLType = UrlType.External;
href.URLState = UrlState.Valid;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if(response.StatusCode == HttpStatusCode.Redirect)
{
//TODO: Redirects
href.URLState = UrlState.Redirect;
}
}
catch(WebException wex)
{
href.URLState = UrlState.Broken;
}
_page.Links.Add(href);
_webRequestComplete++;
request.EndGetResponse(result);
}
两个递增变量,以确保这两个数都是平等的,而且在许多情况下,他们不是,我最终会陷入无限循环。
您需要详细说明您的问题。对于第一个(异步不会返回),这很容易修复,有一个超时,并假设在超时之后,如果它不返回它是无效的。对于误报,你需要确定什么是误报。对于404重定向,我不明白你是怎么得到的,要么你得到了301/302的回应,要么你没有。你需要详细阐述一个好的答案。 – casperOne 2011-01-05 16:07:09
永远不会返回我的意思是,即使我的webrequest有超时延迟,我的委托方法也永远不会被触发。我相信,它至少应该返回一个超时代码的响应。但不是。我的意思是误报,或者一个页面在其重定向或者页面声明为破坏(404)时表明为破坏,但其实际有效。让我知道你是否需要更多信息。 – 2011-01-05 16:16:46