从 HttpWebRequest 和 HttpWebResponse 获取 Http 状态代码编号(200、301、404 等) [英] Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

查看:29
本文介绍了从 HttpWebRequest 和 HttpWebResponse 获取 Http 状态代码编号(200、301、404 等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从 HttpWebRequest 返回的 HttpWebResponse 对象中获取 HTTP 状态代码编号.我希望得到实际数字(200、301,302、404 等)而不是文本描述.(Ok"、MovedPermanently"等)数字是否隐藏在响应对象中某处的属性中?除了创建一个大的开关功能之外还有什么想法吗?谢谢.

I am trying to get the HTTP status code number from the HttpWebResponse object returned from a HttpWebRequest. I was hoping to get the actual numbers (200, 301,302, 404, etc.) rather than the text description. ("Ok", "MovedPermanently", etc.) Is the number buried in a property somewhere in the response object? Any ideas other than creating a big switch function? Thanks.

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 状态代码匹配,例如

HttpStatusCode (the type of response.StatusCode) is an enumeration where the values of the members match the HTTP status codes, e.g.

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

这篇关于从 HttpWebRequest 和 HttpWebResponse 获取 Http 状态代码编号(200、301、404 等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆