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

我正在尝试从HttpWebResponse返回HttpWebResponse对象的HTTP状态代码号。 我希望得到实际的数字(200,301,302,404等),而不是文字说明。 (“Ok”,“MovedPermanently”等)数字是否被埋在响应对象某处的属性中? 除了创build一个大开关function以外的任何想法? 谢谢。

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

HttpStatusCode ( response.StatusCode的types)是成员的值与HTTP状态码匹配的枚举,例如

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

你必须小心,4xx和5xx范围内的服务器响应会引发WebException。 您需要捕获它,然后从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)