【问题标题】:Checking if URL is Valid -404/Not Found检查 URL 是否有效 -404/未找到
【发布时间】:2017-12-14 02:40:48
【问题描述】:

我正在使用以下方法来检查一个 URL 是否存在或是否有效。

class MyClient : WebClient
{
    public bool HeadOnly { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest req = base.GetWebRequest(address);

        if (HeadOnly && req.Method == "GET")
        {
            req.Method = "HEAD";
        }
        return req;
    }
}

private static Boolean CheckURL(string url)
{
    using (MyClient myclient = new MyClient())
    {
        try
        {
            myclient.HeadOnly = true;
            // fine, no content downloaded
            string s1 = myclient.DownloadString(url);
            return true;
        }
        catch (Exception error)
        {
            return false;
        }
    }
}

我的方法正确吗?如何向用户显示已检查 URL 的状态,例如:404、成功等?

请指教..

【问题讨论】:

  • 您需要查看 WebException 暴露的状态码:Web Response status code可能重复
  • 你可能还应该包含一个可信的用户代理标题。
  • @AlexK。您介意将其添加为答案吗..
  • 您可以自己关闭此问题作为副本。

标签: c# .net network-programming system.web


【解决方案1】:

这是你的答案。

public static void isURLExist(string url)
    {
        try
        {
            WebRequest req = WebRequest.Create(url);

            WebResponse res = req.GetResponse();

            Console.WriteLine("Url Exists");
        }
        catch (WebException ex)
        {
            Console.WriteLine(ex.Message);
            if (ex.Message.Contains("remote name could not be resolved"))
            {
                Console.WriteLine("Url is Invalid");
            }
        }
    }

【讨论】:

  • 具体信息取决于您的要求。
  • WebResponse 实现了 IDisposable - 你应该确保将其丢弃
猜你喜欢
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 2012-08-13
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多