Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace HTTPServer
- {
- public enum RequestMethod
- {
- GET,
- POST,
- HEAD
- }
- public enum HTTPVersion
- {
- HTTP10,
- HTTP11,
- HTTP09
- }
- class Request
- {
- string[] requestLines;
- RequestMethod method;
- public string relativeURI;
- Dictionary<string, string> headerLines;
- public Dictionary<string, string> HeaderLines
- {
- get { return headerLines; }
- }
- HTTPVersion httpVersion;
- string requestString;
- string[] contentLines;
- public Request(string requestString)
- {
- this.requestString = requestString;
- }
- /// <summary>
- /// Parses the request string and loads the request line, header lines and content, returns false if there is a parsing error
- /// </summary>
- /// <returns>True if parsing succeeds, false otherwise.</returns>
- public bool ParseRequest()
- {
- //TODO: parse the receivedRequest using the \r\n delimeter
- requestLines = requestString.Split('\n'); //Msh rady y-split xD
- // check that there is atleast 3 lines: Request line, Host Header, Blank line (usually 4 lines with the last empty line for empty content)
- // Validate blank line exists
- // Load header lines into HeaderLines dictionary
- return (ValidateBlankLine() && ParseRequestLine() && LoadHeaderLines());
- }
- private bool ParseRequestLine()
- {
- bool parsed = false;
- bool HTTP = false;
- string request = requestLines[0];
- string[] get = request.Split(' ');
- if (get[0] == "GET")
- {
- method = RequestMethod.GET;
- parsed = true;
- }
- else if (get[0] == "POST")
- {
- method = RequestMethod.POST;
- parsed = true;
- }
- else if (get[0] == "HEAD")
- {
- method = RequestMethod.HEAD;
- parsed = true;
- }
- // Parse Request line
- relativeURI = get[1];
- if (get[2] == "HTTP09")
- {
- httpVersion = HTTPVersion.HTTP09;
- HTTP = true;
- }
- else if (get[2] == "HTTP10")
- {
- httpVersion = HTTPVersion.HTTP10;
- HTTP = true;
- }
- else if (get[2] == "HTTP11")
- {
- httpVersion = HTTPVersion.HTTP11;
- HTTP = true;
- }
- return parsed & HTTP;
- }
- private bool ValidateIsURI(string uri)
- {
- return Uri.IsWellFormedUriString(uri, UriKind.RelativeOrAbsolute);
- }
- private bool LoadHeaderLines()
- {
- int counter = 1;
- bool Loaded = false;
- while (requestLines[counter] != "\r\n")
- {
- string[] headrs = requestLines[counter].Split(':');
- headerLines.Add(headrs[0], headrs[1]);
- counter++;
- Loaded = true;
- }
- return Loaded;
- }
- private bool ValidateBlankLine()
- {
- for(int i=0;i<requestLines.Length;i++)
- {
- if (requestLines[i] == "\r\n")
- return true;
- }
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement