【问题标题】:What is the absolute safest way to find out if a URL exists or not? [duplicate]找出 URL 是否存在的绝对最安全的方法是什么? [复制]
【发布时间】:2020-09-29 04:50:57
【问题描述】:

我确实意识到有不同的方法可以检查 C# 和其他语言的网站是否存在。但是,我开始明白其中一些效果并不好。例如这段代码:

        WebClient client = new WebClient();
        try
        {
            string response = client.DownloadString(url);
            return true;  // Successful -> the website does exist.
        }
        catch
        {
            return false; // Unsuccessful -> the website doesn't exist.
        }

没有检测到www.bb.com,尽管这个网站显然确实存在。为了绝对安全,我应该使用什么代码?

【问题讨论】:

  • "URL 存在与否?" 将它们写为文本时存在。但是,如果您想检查远程资源是否存在,则必须对其进行刺激。您可以 ping 域,但它可能无法令人满意,或者您可以发送一个 head 请求,这可能大部分时间都有效。
  • 说实话URL exists 定义太模糊了。例如想象一下,在公司网络上,您可能拥有使用私有 DNS 的 Intranet 资源,因此甚至无法公开解析。同时,公司网络可能会阻止公共互联网访问,从而阻止您访问它。最后,正如@MichaelRandall 所指出的,资源实际上可能暂时不可用,或者您可能有 ISP 或其他网络问题(例如 SSL/TLS 密码协商、时间偏差等)。试图从客户端机器上声明网站可用性是徒劳的。

标签: c# url webclient


【解决方案1】:

鉴于:

  1. 您链接的站点需要在 User-Agent 字符串中设置主要浏览器之一
  2. HttpClient 比 WebClient 更推荐和更新

你可以这样做:

    using System;
    using System.Net.Http;
    using System.Threading.Tasks;

    namespace resourcechecker
    {
        class Program
        {
            static HttpClient client = new HttpClient();

            public async static Task<bool> ResourceExists(HttpClient client, string url)
            {
                HttpResponseMessage response;
                response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }


            static void Main(string[] args)
            {
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0");
                string url = "http://www.bb.com/";
                Console.WriteLine($"It is {ResourceExists(client, url).Result} that {url} exists");
            }
        }
    }

但是,如果测试计算机的 IP 地址被阻止访问该 Web 服务器,这仍然可能给出错误的答案

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 2011-03-08
    • 2012-04-02
    • 2011-05-25
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    相关资源
    最近更新 更多