在C#中解析原始HTTP响应以获取状态代码

时间:2011-07-21 16:16:15

标签: c# http sockets httpresponse

是否有一种简单的方法来解析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 enum吗?

我使用的是基于套接字的方法,无法改变我收到回复的方式。我只会使用这个字符串。

6 个答案:

答案 0 :(得分:5)

编辑考虑到“我正在使用基于套接字的方法,并且无法改变我获得响应的方式。我只会使用此字符串来处理”。

怎么样

  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)

答案 1 :(得分:4)

HTTP是一个非常简单的协议,以下应该非常可靠地获取状态代码(更新为更强大):

int statusCodeStart = httpString.IndexOf(' ') + 1;
int statusCodeEnd = httpString.IndexOf(' ', statusCodeStart);

return httpString.Substring(statusCodeStart, statusCodeEnd - statusCodeStart);

如果你真的想要,你可以添加一个健全性检查以确保字符串以“HTTP”开头,但是如果你想要健壮性,你也可以只实现一个HTTP解析器。

说实话,这可能会做! : - )

httpString.Substring(9, 3);

答案 2 :(得分:2)

如果它只是一个字符串,你不能只使用正则表达式来提取状态代码吗?

答案 3 :(得分:1)

执行DD59建议或使用正则表达式。

答案 4 :(得分:1)

这会更新标记的答案以处理一些极端情况:

    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;
    }

答案 5 :(得分:0)

因为状态代码的格式保持不变,你可以使用这样的东西。

var responseArray = Regex.Split(response, "\r\n");
 if(responseArray.Length)>0
 {
 var statusCode = (int)responseArray[0].split(' ')[1];
 }