我试图让从HTTP状态代码号HttpWebResponse
从返回的对象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());
Console.Write((int)response.StatusCode);
HttpStatusCode (类型response.StatusCode
)是其中成员的值匹配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());
只是要挟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;
}
//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)
文章来源: Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse