public HttpRequest( string path, string method = "GET", HttpHeader header = null, string encoding = "utf-8") { _path = path; _method = method; _encoding = Encoding.GetEncoding(encoding); if (header != null) { _header.Add(header); } }
/// <summary> /// Parsing Http key value pairs from header /// </summary> /// <param name="httpRequest">/HttpRequest</param> public bool ParseRequestFromHeader(string httpRequest) { string[] header = httpRequest.Split("\r\n"); if (header.Length < 1) { return(false); } string[] splittedverb = header[HTTPVERBPOS].Split(" "); if (splittedverb.Length != 3) { return(false); } Enum.TryParse(splittedverb[0], out HttpMethods methodTemp); HttpMethod = methodTemp; HttpRequest = splittedverb[1].Split("/", StringSplitOptions.RemoveEmptyEntries).ToList(); HttpVersion = splittedverb[2]; bool isBody = false; for (int i = 1; i < header.Length; i++) { if (String.IsNullOrWhiteSpace(header[i])) { isBody = true; ContentLength = GetContentLength(); continue; } if (!isBody) { string[] temp = header[i].Split(":", 2); HttpHeader.Add(temp[0], temp[1]); } else { if (!string.IsNullOrEmpty(HttpBody)) { HttpBody += "\r\n"; } HttpBody += $"{header[i]}"; } } if (ContentLength > 0 && ContentLength >= HttpBody.Length) { HttpBody = HttpBody.Substring(0, ContentLength); } return(true); }
public HttpHeader ReadHeader() { var header = new HttpHeader(); while (true) { var line = ReadLine(); if (line == "") { break; } var i = line.IndexOf(':'); if (i > 0) { header.Add( line.Substring(0, i).Trim(), line.Substring(i + 1).Trim()); } } return(header); }