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

时间:2009-08-25 20:39:30

标签: c# .net http httpwebrequest

我正在尝试从HttpWebResponse返回的HttpWebRequest对象中获取HTTP状态代码。我希望得到实际数字(200,301,302,404等),而不是文字说明。 (“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 个答案:

答案 0 :(得分:356)

Console.Write((int)response.StatusCode);

HttpStatusCoderesponse.StatusCode的类型)是一个枚举,其中成员的值与HTTP状态代码匹配,例如

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}

答案 1 :(得分:234)

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

try
{
    wResp = (HttpWebResponse)wReq.GetResponse();
    wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}

答案 2 :(得分:14)

根据' 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());

答案 3 :(得分:9)

只需将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;
}

答案 4 :(得分:3)

//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)