Beispiel #1
0
        public void HttpHeaderCollection_Get()
        {
            HttpHeaderCollection headers;
            DateTime             date1 = new DateTime(2005, 11, 5, 11, 54, 15);
            DateTime             date2 = new DateTime(2005, 11, 6, 11, 54, 15);

            headers = new HttpHeaderCollection("GET", "/foo.htm");
            headers.Add("String", "Hello World!");
            headers.Add("Int", "10");
            headers.Add("Date", "Sat, 05 Nov 2005 11:54:15 GMT");

            Assert.AreEqual("Hello World!", headers.Get("string", null));
            Assert.AreEqual("Hello World!", headers.Get("STRING", null));
            Assert.AreEqual("foobar", headers.Get("Foobar", "foobar"));
            Assert.IsNull(headers.Get("Foobar", null));

            Assert.AreEqual(10, headers.Get("int", 0));
            Assert.AreEqual(10, headers.Get("INT", 0));
            Assert.AreEqual(77, headers.Get("Foo", 77));
            Assert.AreEqual(88, headers.Get("String", 88));

            Assert.AreEqual(date1, headers.Get("date", DateTime.MinValue));
            Assert.AreEqual(date1, headers.Get("DATE", DateTime.MinValue));
            Assert.AreEqual(date2, headers.Get("foo", date2));
            Assert.AreEqual(date2, headers.Get("string", date2));
        }
Beispiel #2
0
        public void HttpHeaderCollection_BasicHeaders()
        {
            HttpHeaderCollection headers;

            headers = new HttpHeaderCollection(HttpStatus.OK, "OK");
            headers.Add("test1", "value1");
            Assert.AreEqual("value1", headers["test1"]);
            Assert.IsNull(headers["test2"]);
            headers.Add("test2", "value2");
            Assert.AreEqual("value2", headers["test2"]);
            headers.Add("test1", "new");
            Assert.AreEqual("value1, new", headers["test1"]);
            headers["test1"] = "value1";
            Assert.AreEqual("value1", headers["test1"]);
        }
        public void Add_HeaderIsRepeating_AddsSameHeader()
        {
            // Arrange
            var headers = new HttpHeaderCollection(_initialHeaders);

            // Act
            var sameHeader = new HttpHeader(headers.ElementAt(0).Name, headers.ElementAt(0).Value);

            headers.Add(sameHeader);

            // Assert
            Assert.That(headers.Count(), Is.EqualTo(7));
            Assert.That(headers.Last(), Is.SameAs(sameHeader));

            var headersString = headers.ToString();

            Assert.That(headersString, Is.EqualTo(@"Accept: text/html, application/xhtml+xml, image/jxr, */*
Accept-Language: ru-RU
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299
Accept-Encoding: gzip, deflate
Host: allitebooks.com
Connection: Keep-Alive
Accept: text/html, application/xhtml+xml, image/jxr, */*

"));

            var binary = headers.ToArray();

            Assert.That(binary, Is.EquivalentTo(headersString.ToAsciiBytes()));
        }
Beispiel #4
0
        public void AddHeaderWithEmptyKeyShouldThrowException()
        {
            HttpHeader httpHeader = new HttpHeader(string.Empty, "pesho");

            HttpHeaderCollection headerCollection = new HttpHeaderCollection();

            Assert.Throws <BadRequestException>(() => headerCollection.Add(httpHeader));
        }
Beispiel #5
0
        public void AddHeaderWithEmptyValueShouldThrowException()
        {
            HttpHeader httpHeader = new HttpHeader("name", string.Empty);

            HttpHeaderCollection headerCollection = new HttpHeaderCollection();

            Assert.Throws <BadRequestException>(() => headerCollection.Add(httpHeader));
        }
Beispiel #6
0
        public void TryGetInvalidHeaderShouldReturnNull()
        {
            HttpHeader httpHeader = new HttpHeader("name", "pesho");

            HttpHeaderCollection headerCollection = new HttpHeaderCollection();

            headerCollection.Add(httpHeader);

            Assert.Null(headerCollection.GetHeader("age"));
        }
Beispiel #7
0
        public void TryGetValidHeaderShouldReturnIt()
        {
            HttpHeader httpHeader = new HttpHeader("name", "pesho");

            HttpHeaderCollection headerCollection = new HttpHeaderCollection();

            headerCollection.Add(httpHeader);

            Assert.Equal <HttpHeader>(httpHeader, headerCollection.GetHeader(httpHeader.Key));
        }
Beispiel #8
0
        public void TryGetHeaderWithoutKeyShouldThrowException()
        {
            HttpHeader httpHeader = new HttpHeader("name", "pesho");

            HttpHeaderCollection headerCollection = new HttpHeaderCollection();

            headerCollection.Add(httpHeader);

            Assert.Throws <BadRequestException>(() => headerCollection.GetHeader(string.Empty));
        }
Beispiel #9
0
        public void GetContainedHeaderShouldReturnTrue()
        {
            HttpHeader httpHeader = new HttpHeader("name", "pesho");

            HttpHeaderCollection headerCollection = new HttpHeaderCollection();

            headerCollection.Add(httpHeader);

            Assert.True(headerCollection.ContainsHeader(httpHeader.Key));
        }
        public void Add_HeaderIsNull_ThrowsArgumentNullException()
        {
            // Arrange
            var headers = new HttpHeaderCollection(_initialHeaders);

            // Act & Assert
            var ex = Assert.Throws <ArgumentNullException>(() => headers.Add(null));

            Assert.That(ex.ParamName, Is.EqualTo("header"));
        }
        public void Test_HttpHeaderCollection_Add_Remove()
        {
            HttpHeaderCollection collection = new HttpHeaderCollection();

            collection.Add("k1", "abc");
            Assert.AreEqual("abc", collection["k1"]);

            int count = 0;

            try {
                collection.Add(null, "abc");
            }
            catch (ArgumentException) {
                count++;
            }

            try {
                collection.Add("k2", null);
            }
            catch (ArgumentException) {
                count++;
            }

            try {
                collection.Remove("");
            }
            catch (ArgumentException) {
                count++;
            }

            Assert.AreEqual(3, count);


            collection.Remove("k1");
            Assert.IsNull(collection["k1"]);
        }
Beispiel #12
0
        /// <summary>
        /// Inspects the <see cref="RequestBase"/> and creates a <see cref="HttpHeaderCollection"/> with applicable headers.
        /// </summary>
        /// <param name="request">The <see cref="RequestBase"/>.</param>
        /// <param name="collectedHttpHeaders"></param>
        /// <returns>A new instance of the <see cref="HttpHeaderCollection"/> class.</returns>
        /// <exception cref="ArgumentNullException">The value of '<paramref name="request"/>' and '<paramref name="collectedHttpHeaders"/>' cannot be null. </exception>
        public void CollectRequestHeaders(RequestBase request, HttpHeaderCollection collectedHttpHeaders)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (collectedHttpHeaders == null)
            {
                throw new ArgumentNullException(nameof(collectedHttpHeaders));
            }

            // ReSharper disable once SuspiciousTypeConversion.Global Third-party developers can provide the implementation.
            if (request is INeedAuthorization)
            {
                collectedHttpHeaders.Add(this.authorizationContext.CreateBearer());
            }
        }
Beispiel #13
0
        internal HttpRequest(TcpClient request)
        {
            _stream = request.GetStream();
            string firstLine = GetNextLine();

            if (!firstLine.StartsWith("GET"))
            {
                throw new NotSupportedException();
            }
            string[] firstLineTokens = firstLine.Split(' ');
            if (firstLineTokens.Length != 3)
            {
                throw new NotSupportedException();
            }
            _protocol   = firstLineTokens[2];
            _requestUri = new Uri(firstLineTokens[1], UriKind.RelativeOrAbsolute);
            string headerLine;

            while ((headerLine = GetNextLine()).Length != 0)
            {
                _headers.Add(headerLine);
            }
        }
        public void op_Add_IHttpHeader()
        {
            var obj = new HttpHeaderCollection();
            var item = new HttpHeader("name", "value");

            Assert.Equal(0, obj.Count);

            obj.Add(item);

            Assert.Equal(1, obj.Count);
        }
Beispiel #15
0
        public static HttpRequest Parse(string request)
        {
            string[] requestLines = request.Split("\r\n");

            string[] firstLineComponents = requestLines[0].Split(' ');

            if (firstLineComponents.Length != 3)
            {
                throw new ArgumentException("HTTP request line is invalid", nameof(request));
            }

            if (!Enum.TryParse(firstLineComponents[0], out HttpRequestMethod method))
            {
                throw new ArgumentException("HTTP request method is invalid", nameof(request));
            }

            string url = firstLineComponents[1];

            string[] pathComponents = url.Split('?');

            if (pathComponents.Length > 2)
            {
                throw new ArgumentException("HTTP query is invalid", nameof(request));
            }

            string path = pathComponents[0];

            Dictionary <string, object> queryData = null;

            KeyValuePair <string, object> ParseQueryString(string part)
            {
                string[] keyValuePair = part.Split('=');

                if (keyValuePair.Length != 2)
                {
                    throw new ArgumentException("Query string key/value pair does not contain two part", nameof(part));
                }

                return(new KeyValuePair <string, object>(keyValuePair[0], keyValuePair[1]));
            }

            if (pathComponents.Length == 2)
            {
                string query = pathComponents[1];

                if (query.Contains('#'))
                {
                    query = query.Split('#', 1).Single();
                }

                queryData = new Dictionary <string, object>(query.Split('&').Select(ParseQueryString));
            }

            string protocol = firstLineComponents[2];

            if (protocol != Constants.HttpProtocolVersion)
            {
                throw new ArgumentException("HTTP protocol version is invalid", nameof(request));
            }

            HttpHeaderCollection headers = new HttpHeaderCollection();

            int lastLineIndex = 0;

            for (int lineIndex = 1; lineIndex < requestLines.Length; ++lineIndex)
            {
                lastLineIndex = lineIndex;

                string line = requestLines[lineIndex];

                if (line == string.Empty)
                {
                    break;
                }

                string[] keyValuePair = line.Split(": ", 2);

                if (keyValuePair.Length != 2)
                {
                    throw new ArgumentException("A header is invalid", nameof(request));
                }

                headers.Add(keyValuePair[0], keyValuePair[1]);
            }

            if (!headers.Contains("Host"))
            {
                throw new ArgumentException("Host header not found", nameof(request));
            }

            Dictionary <string, object> formData = null;

            {
                int formDataLineIndex = lastLineIndex + 1;

                if (requestLines.Length > formDataLineIndex)
                {
                    string formDataLine = requestLines[formDataLineIndex];

                    if (formDataLine != string.Empty)
                    {
                        formData = new Dictionary <string, object>(formDataLine.Split('&')
                                                                   .Select(ParseQueryString));
                    }
                }
            }

            HttpCookieCollection httpCookieCollection = new HttpCookieCollection();

            if (headers.TryGetHeader("Cookie", out HttpHeader header))
            {
                foreach (string[] parts in header.Value.Split("; ").Select(cookie => cookie.Split('=')))
                {
                    httpCookieCollection.Add(new HttpCookie(parts[0], parts[1]));
                }
            }

            return(new HttpRequest(path, url, formData, queryData, method, headers, httpCookieCollection));
        }