[英]Parse a raw HTTP Response in C# to get the Status Code
是否有一种简单的方法来解析 HTTP 响应字符串,如下所示:
"HTTP/1.1 200 OK\r\nContent-Length: 1433\r\nContent-Type: text/html\r\nContent-Location: http://server/iisstart.htm\r\nLast-Modified: Fri, 21 Feb 2003 23:48:30 GMT\r\nAccept-Ranges: bytes\r\nETag: \"09b60bc3dac21:1ca9\"\r\nServer: Microsoft-IIS/6.0\r\nX-Po"
我想获得状态码。 我不一定需要将其转换为HttpResponse
object,但这与解析状态代码一样是可以接受的。 我可以将其解析为HttpStatusCode
枚举吗?
我正在使用基于 sockets 的方法,并且无法改变我得到回复的方式。 我只会使用这个字符串。
编辑考虑到“我正在使用基于 sockets 的方法,并且无法改变我得到回复的方式。我只会使用这个字符串”。
怎么样
string response = "HTTP/1.1 200 OK\r\nContent-Length: 1433\r\nContent-Type: text/html\r\nContent-Location: http://server/iisstart.htm\r\nLast-Modified: Fri, 21 Feb 2003 23:48:30 GMT\r\nAccept-Ranges: bytes\r\nETag: \"09b60bc3dac21:1ca9\"\r\nServer: Microsoft-IIS/6.0\r\nX-Po";
string code = response.Split(' ')[1];
// int code = int.Parse(response.Split(' ')[1]);
我最初是这样建议的:
HttpWebRequest webRequest =(HttpWebRequest)WebRequest.Create("http://www.gooogle.com/");
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
int statuscode = (int)response.StatusCode)
HTTP 是一个非常简单的协议,以下应该非常可靠地获取状态代码(更新为更强大一点):
int statusCodeStart = httpString.IndexOf(' ') + 1;
int statusCodeEnd = httpString.IndexOf(' ', statusCodeStart);
return httpString.Substring(statusCodeStart, statusCodeEnd - statusCodeStart);
如果你真的想要,你可以添加一个完整性检查以确保字符串以“HTTP”开头,但是如果你想要健壮性,你也可以只实现 HTTP 解析器。
老实说,这可能会::-)
httpString.Substring(9, 3);
如果它只是一个字符串,你能不能只使用正则表达式来提取状态码?
这会更新标记的答案以处理一些极端情况:
static HttpStatusCode? GetStatusCode(string response)
{
string rawCode = response.Split(' ').Skip(1).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(rawCode) && rawCode.Length > 2)
{
rawCode = rawCode.Substring(0, 3);
int code;
if (int.TryParse(rawCode, out code))
{
return (HttpStatusCode)code;
}
}
return null;
}
要么按照 DD59 的建议去做,要么使用正则表达式。
因为状态码的格式保持不变,你可能可以像这样使用 smthing。
var responseArray = Regex.Split(response, "\r\n");
if(responseArray.Length)>0
{
var statusCode = (int)responseArray[0].split(' ')[1];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.