【问题标题】:WebRequest get page w/o exceptions?WebRequest 获取没有异常的页面?
【发布时间】: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;
        }

【问题讨论】:

    标签: c# httpwebrequest httpwebresponse


    【解决方案1】:

    HttpWebResponse 类公开了一个 StatusCode 属性,该属性从 HttpStatusCode 枚举中返回一个值。在非错误情况下,这会直接为您提供状态码(404 未找到、403 未经授权、301 永久移动、200 正常等等)。在错误情况下,WebException 类公开了一个 Status 属性 - 取自不同的枚举,但您将能够从我认为的情况中识别出您想要的情况。

    【讨论】:

    • 我认为你的意思是当它的 404/403/等出现异常时,没有办法获得页面状态。我会记住这一点的。
    • 是的,这些“错误”HTTP 状态之一的行为是抛出 WebException。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 2013-09-18
      相关资源
      最近更新 更多