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


289

我正在尝试从从HttpWebResponse返回的对象中获取HTTP状态代码号HttpWebRequest。我希望获得实际数字(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());

对于相反的操作:httpResponse.HTTPStatusCode =(HttpStatusCode)Enum.ToObject(typeof(HttpStatusCode),404))
Leandro

Answers:


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

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

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

1
但是在webexception的“ connectfailure”异常的情况下,我得到的响应为null,在这种情况下,我如何获取httpstatus代码
Rusty

10
@rusty:如果连接失败,因此无法发送请求,也无法接收到响应,则不会有任何http状态代码。
奥利弗

3
如何获得HTTP Substatus值?例如,404.13的内容长度太大参考:iis.net/configreference/system.webserver/security/...
Kiquenet

9
奖金:bool success = ((int)response.StatusCode) >= 200 && ((int)response.StatusCode) < 300;
阿兰2015年

12
@Alain双倍奖金;布尔成功= response.IsSuccessStatusCode;
htxryan

244

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

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

我很高兴您提到4xx和5xx,因为我遇到了程序无法正常运行的问题。我应该指出,尽管当前的.NET框架会通知您任何未捕获的异常,所以这也是理所当然的。
乔尔·特劳格

另外,以前可以使用[DebuggerNonUserCode]装饰方法的方法,当引发异常时,Debugger不会在该方法中停止。以这种方式可以包装设计不当的异常并将其忽略。但是现在需要一个注册表设置
crokusek '17

21

按照“ 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());

HttpWebResponse实现IDisposable,因此处理它可能很棘手。您可以改用以下代码,使您可以在using块内声明“响应”:public HttpWebResponse GetSafeResponse(HttpWebRequest request){试试{返回(HttpWebResponse)request.GetResponse(); } catch(WebException we){返回(HttpWebResponse)we.Response; }
DesertFoxAZ

11

只是要挟StatusCodeint

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

1
这是vb.net,OP使用C#
Kemuel Sanchez

2
..并且我正在使用vb。很高兴这个答案在这里。
提请
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.