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

我试图从HttpWebRequest返回的HttpWebResponse对象中获取HTTP状态码号码。我希望得到实际的数字(200,301,302,404等),而不是文本描述。(“Ok”,“movedpermanent”等)数字是否被埋在响应对象的某个属性中?除了创建一个大型开关函数,还有什么其他想法吗?谢谢。

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());
364709 次浏览
Console.Write((int)response.StatusCode);

HttpStatusCode(类型为response.StatusCode)是一个枚举,其中成员的值匹配HTTP状态码,例如:

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

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

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

根据'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());
//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)

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

下面是我处理这种情况的方法。

//string details = ...
//...
catch (WebException ex)
{
HttpStatusCode statusCode = ((HttpWebResponse)ex.Response).StatusCode;
if (statusCode == HttpStatusCode.Unauthorized)
{
Reconnect();
//...
}
else if (statusCode == HttpStatusCode.NotFound)
{
FileLogger.AppendToLog("[ERROR] Not Found: " + details);
}
else
{
FileLogger.AppendToLog("[ERROR] " + ex.Message + ": " + details);
}
}