有没有一种简单的方法来解析 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
对象,但这是可以接受的,而且只需解析出状态代码。我能否将其解析为 HttpStatusCode
枚举?
我使用的是基于套接字的方法,无法改变我获得响应的方式。我只会使用这个字符串。
最佳答案
编辑考虑到“我正在使用基于套接字的方法并且无法改变我获得响应的方式。我将只使用这个字符串”。
怎么样
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)
关于c# - 在 C# 中解析原始 HTTP 响应以获取状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6779303/