如何使用 Html Agility Pack 使请求超时
我正在向当前离线(故意)的远程 Web 服务器发出请求。
我想找出使请求超时的最佳方法。基本上,如果请求运行时间超过“X”毫秒,则退出请求并返回 null
响应。
目前,网络请求只是坐在那里等待响应......
我将如何最好地解决这个问题?
这是当前的代码片段
public JsonpResult About(string HomePageUrl)
{
Models.Pocos.About about = null;
if (HomePageUrl.RemoteFileExists())
{
// Using the Html Agility Pack, we want to extract only the
// appropriate data from the remote page.
HtmlWeb hw = new HtmlWeb();
HtmlDocument doc = hw.Load(HomePageUrl);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class='wrapper1-border']");
if (node != null)
{
about = new Models.Pocos.About { html = node.InnerHtml };
}
//todo: look into whether this else statement is necessary
else
{
about = null;
}
}
return this.Jsonp(about);
}
I'm making a request to a remote web server that is currently offline (on purpose).
I'd like to figure out the best way to time out the request. Basically if the request runs longer than "X" milliseconds, then exit the request and return a null
response.
Currently the web request just sits there waiting for a response.....
How would I best approach this problem?
Here's a current code snippet
public JsonpResult About(string HomePageUrl)
{
Models.Pocos.About about = null;
if (HomePageUrl.RemoteFileExists())
{
// Using the Html Agility Pack, we want to extract only the
// appropriate data from the remote page.
HtmlWeb hw = new HtmlWeb();
HtmlDocument doc = hw.Load(HomePageUrl);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class='wrapper1-border']");
if (node != null)
{
about = new Models.Pocos.About { html = node.InnerHtml };
}
//todo: look into whether this else statement is necessary
else
{
about = null;
}
}
return this.Jsonp(about);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过以下方法检索您的 url 网页:
并使用 HTML Agility 包并检索 html 标签,如下所示:
Retrieve your url web page through this method:
And to use the HTML Agility pack and retrive the html tag like this:
Html Agility Pack 是开源的。这就是为什么你可以自己修改源代码。
首先将此代码添加到类 HtmlWeb 中:
然后找到此方法
并修改它:
或者类似的东西:
Html Agility Pack is open souce. Thats why you may modify source yurself.
For first add this code to class HtmlWeb:
Then find this method
and modify it:
Or something like that:
我必须对最初发布的代码进行一些小调整
然后我修改了我的
RemoteFileExists
扩展方法以设置超时在这种方法中,如果我的超时在
RemoteFileExists
可以确定之前触发标头响应,那么我的bool
将返回 false。I had to make a small adjustment to my originally posted code
Then I modified my
RemoteFileExists
extension method to have a timeoutIn this approach, if my timeout fires before
RemoteFileExists
can determine the header response, then mybool
will return false.您可以使用标准 HttpWebRequest 来获取远程资源并设置 超时属性。如果生成的 HTML 成功,则将其提供给 HTML Agility Pack 进行解析。
You could use a standard HttpWebRequest to fetch the remote resource and set the Timeout property. Then feed the resulting HTML if it succeeds to HTML Agility Pack for parsing.