예제 #1
0
        private async Task <HttpResponseMessage> ReadResponseHeadAsync(ByteStreamReader reader, HttpRequestMessage request)
        {
            // initialize the response
            var response = new HttpResponseMessage {
                RequestMessage = request
            };

            // read the first line of the response
            string line = await reader.ReadLineAsync().ConfigureAwait(false);

            string[] pieces = line.Split(new[] { ' ' }, 3);
            if (pieces[0] != "HTTP/1.1")
            {
                throw new HttpRequestException("The HTTP version the response is not supported.");
            }

            response.StatusCode   = (HttpStatusCode)int.Parse(pieces[1]);
            response.ReasonPhrase = pieces[2];

            // read the headers
            response.Content = new ByteArrayContent(new byte[0]);
            while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null && line != string.Empty)
            {
                pieces = line.Split(new[] { ":" }, 2, StringSplitOptions.None);
                if (pieces[1].StartsWith(" "))
                {
                    pieces[1] = pieces[1].Substring(1);
                }

                if (!response.Headers.TryAddWithoutValidation(pieces[0], pieces[1]))
                {
                    if (!response.Content.Headers.TryAddWithoutValidation(pieces[0], pieces[1]))
                    {
                        throw new InvalidOperationException($"The header '{pieces[0]}' could not be added to the response message or to the response content.");
                    }
                }
            }

            return(response);
        }