WebRequest and System.Net.WebException on 404, slo

2019-06-05 09:26发布

问题:

I am using a WebRequest to check if a web page or media (image) exist. On GetResponse i get a System.Net.WebException exception. I ran through 100 links and it feels like its going slower then it should. Is there a way to not get this exception or handle this more gracefully?

    static public bool CheckExist(string url)
    {
        HttpWebRequest wreq = null;
        HttpWebResponse wresp = null;
        bool ret = false;
        try
        {
            wreq = (HttpWebRequest)WebRequest.Create(url);
            wreq.KeepAlive = true;
            wresp = (HttpWebResponse)wreq.GetResponse();
            ret = true;
        }
        catch (System.Net.WebException)
        {
        }
        finally
        {
            if (wresp != null)
                wresp.Close();
        }
        return ret;
    }

回答1:

Try setting

wreq.Method = "Head";

after the "KeepAlive" line. If the webserver you are calling is smart enough, that will tell it not to return any body contents which should save some time.