예제 #1
0
        public bool TryParseResponse(MemoryStream ms)
        {
            ResponseStream = ms;
            RawContent     = ms.GetBuffer();
            var p = UTF8Encoding.UTF8.GetString(RawContent);

            string[] HeaderAndData = p.Split(new String[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            try
            {
                if (HeaderAndData.Length < 1)
                {
                    throw new FormatException();
                }

                var headerFields = HeaderAndData[0].Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                var MethodResourceversion         = headerFields[0];
                var MethodResourceversionSplitted = MethodResourceversion.Split(' ');

                Version    = Version.Parse(MethodResourceversionSplitted[0].ToLower().Replace("http/", ""));
                StatusCode = Convert.ToInt32(MethodResourceversionSplitted[1]);

                for (int i = 2; i < MethodResourceversionSplitted.Length; i++)
                {
                    StatusMessage += MethodResourceversionSplitted[i] + " ";
                }

                StatusMessage = StatusMessage.Trim();

                for (int i = 1; i < headerFields.Length; i++)
                {
                    var PropertyValue = headerFields[i].Split(new String[] { ": " }, StringSplitOptions.None);

                    var key   = PropertyValue[0].Trim();
                    var value = PropertyValue[1].Trim();

                    if (Headers.Any(v => v.Key.ToLower().Equals(key.ToLower())) && !string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                    {
                        Headers[key] = value;
                    }

                    if (!Headers.ContainsKey(key))
                    {
                        HttpHandler.Log(LogLevel.Warning, "Key \"" + key + "\" is missing in header list");
                    }
                }

                if (!string.IsNullOrEmpty(Headers["Content-Type"]))
                {
                    ContentType = Headers["Content-Type"];
                }
                if (!string.IsNullOrEmpty(Headers["Content-Length"]))
                {
                    ContentLength = Convert.ToInt32(Headers["Content-Length"]);
                }

                if (HeaderAndData.Length >= 2)
                {
                    HasPayload = true;
                    var contentLength = RawContent.Length - HeaderAndData[0].Length - 4;
                    Content = new byte[contentLength];
                    Array.Copy(RawContent, RawContent.Length - contentLength, Content, 0, contentLength);
                }
                return(true);
            }
            catch (Exception e)
            {
                HttpHandler.Log(LogLevel.Error, "Http request parsing error : " + e.Message);
                return(false);
            }
        }