예제 #1
0
        public static RequestInfo Analyze(MemoryStream ms, ref int total)
        {
            ms.Position = 0;
            int iChar, iLoc = 0;

            while ((iChar = ms.ReadByte()) > -1)
            {
                if (iChar.Equals(13))
                {
                    if (ms.ReadByte().Equals(10))
                    {
                        if (ms.ReadByte().Equals(13))
                        {
                            if (ms.ReadByte().Equals(10))
                            {
                                iLoc = (int)(ms.Position - 4);
                                break;
                            }
                        }
                    }
                }
            }
            if (iLoc == 0)
            {
                return(null);
            }

            byte[] _header_buffer = new byte[iLoc];
            ms.Position = 0;
            ms.Read(_header_buffer, 0, iLoc);
            string      _header = Encoding.ASCII.GetString(_header_buffer);
            string      Method  = _header.Substring(0, _header.IndexOf(' '));
            RequestInfo request = null;

            if (Method == "GET")
            {
                request = new RequestInfo(_header);
                request.ParseHeaders();
                return(request);
            }
            else if (Method == "POST")
            {
                Match m = regLen.Match(_header);
                if (!m.Success || !int.TryParse(m.Value.Substring(15), out int content_length))
                {
                    throw new MyException(0, "无请求长度!");
                }
                total = content_length + iLoc + 4;
                if ((iLoc + 4 + content_length) == ms.Length)
                {
                    request = new RequestInfo(_header);
                    byte[] buffer = new byte[content_length];
                    ms.Position = iLoc + 4;
                    ms.Read(buffer, 0, content_length);
                    request.EntityBody = buffer;
                    request.ParseHeaders();
                }
                return(request);
            }
            throw new MyException(0, "错误的HTTP请求!");
        }