Reputation: 6920
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.
Upvotes: 3
Views: 13627
Reputation: 1369
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;
}
Upvotes: 1
Reputation: 30224
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)
Upvotes: 5
Reputation: 12705
coz the format of the status code remains same u can probably use smthing like this.
var responseArray = Regex.Split(response, "\r\n");
if(responseArray.Length)>0
{
var statusCode = (int)responseArray[0].split(' ')[1];
}
Upvotes: 0
Reputation: 86729
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);
Upvotes: 4
Reputation: 7761
If it's just a string could you not just use a regex to extract the status code?
Upvotes: 2