代码之家  ›  专栏  ›  技术社区  ›  James Lawruk

从HttpWebRequest和HttpWebResponse获取Http状态代码(200、301、404等)

  •  261
  • James Lawruk  · 技术社区  · 15 年前

    我正在尝试从中获取HTTP状态代码 HttpWebResponse 对象从 HttpWebRequest . 我希望得到的是实际的数字(200301302404等),而不是文字描述。(“Ok”、“MovedPermanently”等)是埋藏在响应对象中某个属性中的数字吗?除了创建一个大的开关功能,还有其他想法吗?谢谢

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest
                                               .Create("http://www.gooogle.com/");
    webRequest.AllowAutoRedirect = false;
    HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
    //Returns "MovedPermanently", not 301 which is what I want.
    Console.Write(response.StatusCode.ToString());
    
    5 回复  |  直到 12 年前
        1
  •  427
  •   dtb    15 年前
    Console.Write((int)response.StatusCode);
    

    HttpStatusCode (一类) response.StatusCode

    public enum HttpStatusCode
    {
        ...
        Moved = 301,
        OK = 200,
        Redirect = 302,
        ...
    }
    
        2
  •  249
  •   zeldi    13 年前

    您必须小心,4xx和5xx范围内的服务器响应会引发WebException。您需要捕获它,然后从WebException对象获取状态代码:

    try
    {
        wResp = (HttpWebResponse)wReq.GetResponse();
        wRespStatusCode = wResp.StatusCode;
    }
    catch (WebException we)
    {
        wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
    }
    
        3
  •  24
  •   Wojciech Jakubas    8 年前

    根据“dtb”,您需要使用HttpStatusCode,但在“zeldi”之后,您需要特别小心代码响应>=400

    这对我起了作用:

    HttpWebResponse response = null;
    HttpStatusCode statusCode;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException we)
    {
        response = (HttpWebResponse)we.Response;
    }
    
    statusCode = response.StatusCode;
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    sResponse = reader.ReadToEnd();
    Console.WriteLine(sResponse);
    Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
    
        4
  •  14
  •   Marc    6 年前

    StatusCode int .

    var statusNumber;
    try {
       response = (HttpWebResponse)request.GetResponse();
       // This will have statii from 200 to 30x
       statusNumber = (int)response.StatusCode;
    }
    catch (WebException we) {
        // Statii 400 to 50x will be here
        statusNumber = (int)we.Response.StatusCode;
    }
    
        5
  •  4
  •   prestigious    8 年前
    //Response being your httpwebresponse
    Dim str_StatusCode as String = CInt(Response.StatusCode)
    Console.Writeline(str_StatusCode)