Parse a raw HTTP Response in C# to get the Status Code

11,955

Solution 1

EDIT Taking into account "I am using a sockets based approach and cannot change the way I am getting my response. I will only have this string to work with".

How about

  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]);

I had originally suggested this:

  HttpWebRequest webRequest =(HttpWebRequest)WebRequest.Create("http://www.gooogle.com/");
  webRequest.AllowAutoRedirect = false;
  HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
  int statuscode = (int)response.StatusCode)

Solution 2

HTTP is a pretty simple protocol, the following should get the status code out pretty reliably (updated to be a tad more robust):

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

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

If you really wanted to you could add a sanity check to make sure that the string starts with "HTTP", but then if you wanted robustness you could also just implement a HTTP parser.

To be honest this would probably do! :-)

httpString.Substring(9, 3);

Solution 3

If it's just a string could you not just use a regex to extract the status code?

Solution 4

Either do what DD59 suggests or use a regular expression.

Solution 5

This updates the marked answer to handle some corner cases:

    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;
    }
Share:
11,955
Ian R. O'Brien
Author by

Ian R. O'Brien

I've been developing software for the financial services industry for almost seven years. I work in the investment banking arm of a large multi-national bank. My experience on the sell side includes working on a financial CRM system used by equity research, sales, and trading firms in order to distribute research, discover new sales opportunities, and manage interactions with existing and prospective clients. On the buy side I've worked as a consultant for several different hedge funds in order to develop and implement customized software solutions to automate tasks, improve workflow efficiency, and enforce compliance to the SAS 70 auditing standard. I am experienced in multi-tier architecture development using C#, Java, C++, T-SQL/MySQL, JSP, and HTML, and I have used many other languages and technologies. I received a Bachelor's of Science in Computer Engineering from the Thomas J. Watson School of Engineering and Applied Science from Binghamton University. I am conversationally proficient in Norwegian. I am a Duolingo Global Ambassador for the Norwegian Language, and I study the language at the NYU School of Professional Studies and remotely with a private tutor based in Oslo. I host and maintain the site https://www.brunost.org.

Updated on June 04, 2022

Comments

  • Ian R. O'Brien
    Ian R. O'Brien almost 2 years

    Is there a simple way to parse an HTTP Response string such as follows:

    "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"
    

    I would like to get the Status Code. I do not necessarily need to turn this in to an HttpResponse object, but that would be acceptable as well as just parsing out the Status Code. Would I be able to parse that into the HttpStatusCode enum?

    I am using a sockets based approach and cannot change the way I am getting my response. I will only have this string to work with.

  • ShigaSuresh
    ShigaSuresh almost 13 years
    Agreed, according the the OP " I will only have this string to work with." ... so work with the string....
  • Admin
    Admin over 9 years
    I'm not sure how this is supposed to function correctly, as each name/value pair are separated by \r\n, not " ".... You'd want to first split by \r\n then split each of those by space in order to get true name/values...
  • ShigaSuresh
    ShigaSuresh over 9 years
    @tecknik Because he is trying to get the response code which appears after the first string. If you wanted to split the whole thing up into key value pairs you could do that, but he just wanted the get the code out, in this case "200".
  • devprashant
    devprashant about 8 years
    @TechnikEmpire first line is not structured like hash table in http header. Although subsequent lines are structured and can be split at ":" (colon) to get key/value pair for further parsing of headers.
  • Admin
    Admin about 8 years
    @devprashant My point is, having written a fully compliant HTTP/S proxy, that this is a very poor way to parse the headers. In fact this doesn't parse the headers at all, it'll split them a way that will expose the status code string, but absolutely break everything else.