【发布时间】:2011-06-04 02:19:38
【问题描述】:
是否有人知道任何好的链接验证 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 响应,要么你没有。您需要详细说明才能获得好的答案。
-
永不返回我的意思是,不会引发事件,即使我的 webrequest 有超时延迟,我的委托方法也永远不会被命中。我相信,它至少应该给我一个带有超时代码的响应。但它不是。我的意思是误报,要么是页面在其重定向时被声明为损坏,要么页面被声明为损坏(404)但它实际上是有效的。如果您需要更多信息,请告诉我。
标签: c# .net httpwebrequest httpwebresponse