是否有检查,如果外部网页存在一个更快的方法? [英] Is there a faster way to check if an external web page exists?

查看:125
本文介绍了是否有检查,如果外部网页存在一个更快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个方法来检查是否一个页面存在与否:

I wrote this method to check if a page exists or not:

protected bool PageExists(string url)
{
try
    {
        Uri u = new Uri(url);
        WebRequest w = WebRequest.Create(u);

            w.Method = WebRequestMethods.Http.Head;

        using (StreamReader s = new StreamReader(w.GetResponse().GetResponseStream()))
        {
            return (s.ReadToEnd().Length >= 0);
        }
    }
        catch
    {
        return false;
        }
    }

我使用它来检查一组页面(从AAAA-AAAZ迭代),它以秒3和7之间运行整个循环。是否有更快或更有效的方式做到这一点?

I am using it to check a set of pages (iterates from AAAA-AAAZ), and it takes between 3 and 7 seconds to run the entire loop. Is there a faster or more efficient way to do this?

推荐答案

我觉得你的做法是相当不错的,但它会变成只有加入 w.Method = WebRequestMethods.Http下载头。头; 之前调用的GetResponse

I think your approach is rather good, but would change it into only downloading the headers by adding w.Method = WebRequestMethods.Http.Head; before calling GetResponse.

这可以做到这一点:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
request.Method = WebRequestMethods.Http.Head;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
bool pageExists = response.StatusCode == HttpStatusCode.OK;

您可能可能要检查其他状态codeS为好。

You may probably want to check for other status codes as well.

这篇关于是否有检查,如果外部网页存在一个更快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆