English 中文(简体)
WebRequest页面w / o例外吗?
原标题:
  • 时间:2009-04-16 00:22:31
  •  标签:

我想检查页面的状态(404、移动等)。我能怎么做?ATM我做以下只告诉我如果页面存在与否。同时,我怀疑异常使我的代码慢(我测试)

static public bool CheckExist(string url)
        {
            HttpWebRequest wreq = null;
            HttpWebResponse wresp = null;
            bool ret = false;

            try
            {
                wreq = (HttpWebRequest)WebRequest.Create(url);
                wreq.KeepAlive = true;
                //wreq.Method = "HEAD";
                wresp = (HttpWebResponse)wreq.GetResponse();
                ret = true;
            }
            catch (System.Net.WebException)
            {
            }
            finally
            {
                if (wresp != null)
                    wresp.Close();
            }
            return ret;
        }
问题回答

HttpWebResponse类暴露一个StatusCode财产从HttpStatusCode枚举返回一个值。non-error情况下,直接给你这个状态码(404 not found 403未经授权,301永久移动,200 OK等等)。在错误的情况下,WebException类暴露状态属性——来自一个不同的枚举,但是你能够确定的情况下,你想从我想到。

你可以得到http错误代码是这样的:

catch (System.Net.WebException e)
{
    int HttpStatusCode = (int)((HttpWebResponse)e.Response).StatusCode;
}




相关问题
热门标签