private static void CopyHeaders(HttpRequestHeaders input, Windows.Web.Http.Headers.HttpRequestHeaderCollection output)
 {
     foreach (var header in input)
     {
         output.Add(header.Key, GetHeaderValue(header.Key, header.Value));
     }
 }
Exemple #2
0
        // Get header values.

        public List <string> GetHeaderValues(Windows.Web.Http.Headers.HttpRequestHeaderCollection headers, string headerName)
        {
            List <string> list = new List <string>();

            List <KeyValuePair <string, string> > headerList = headers.ToList();
            List <string> values = headerList.Where(kvp => kvp.Key == headerName).Select(kvp => kvp.Value).Distinct().ToList();

            foreach (string str in values)
            {
                list.Add(str.TrimStart(null));
            }
            return(list);
        }
Exemple #3
0
        internal static async Task <string> Get(string url)
        {
            //Create an HTTP client object
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            //Add a user-agent header to the GET request.
            Windows.Web.Http.Headers.HttpRequestHeaderCollection headers = httpClient.DefaultRequestHeaders;
            headers.Add("cache-control", "no-cache");
            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";

            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }
            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri(Constants.BaseURL + url);

            //Send the GET request asynchronously and retrieve the response as a string.
            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                return(httpResponseBody);
            }
            catch (Exception ex)
            {
                return(string.Empty);
            }
        }
Exemple #4
0
        /// <summary>
        /// Copies headers from one <see cref="Windows.Web.Http.HttpRequestMessage"/> instance to another.
        /// </summary>
        /// <param name="source">The source <see cref="Windows.Web.Http.HttpRequestMessage"/> to copy from.</param>
        /// <param name="destination">The destination <see cref="Windows.Web.Http.HttpRequestMessage"/> to copy to.</param>
        public static void CopyHeadersTo(this Windows.Web.Http.Headers.HttpRequestHeaderCollection source, Windows.Web.Http.Headers.HttpRequestHeaderCollection destination)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            foreach (var header in source)
            {
                if (destination.ContainsKey(header.Key))
                {
                    destination.Remove(header.Key);
                }

                destination.Add(header.Key, header.Value);
            }
        }
Exemple #5
0
        /*
         * ----< Function > TruncateTestFunctions
         * ----< Description >
         * This function will truncate any items in the test function table of the api database
         * ----< Description >
         * @Param None
         * @Return None
         */
        public static async void TruncateTestFunctions()
        {
            Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();

            Windows.Web.Http.Headers.HttpRequestHeaderCollection headers = httpClient.DefaultRequestHeaders;

            string header = "ie";

            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri("http://www.kaminfay.com/");

            Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                Debug.WriteLine(httpResponseBody);
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
        }
        private static async Task<RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, RTHttpRequestHeaderCollection rtHeaderCollection)
        {
            HttpContent content = request.Content;

            RTIHttpContent rtContent;
            ArraySegment<byte> buffer;

            // If we are buffered already, it is more efficient to send the data directly using the buffer with the
            // WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by
            // a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter.
            Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false);

            if (contentStream is RTIInputStream)
            {
                rtContent = new RTHttpStreamContent((RTIInputStream)contentStream);
            }
            else if (contentStream is MemoryStream)
            {
                var memStream = contentStream as MemoryStream;
                if (memStream.TryGetBuffer(out buffer))
                {
                    rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count);
                }
                else
                {
                    byte[] byteArray = memStream.ToArray();
                    rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint)byteArray.Length);
                }
            }
            else
            {
                rtContent = new RTHttpStreamContent(contentStream.AsInputStream());
            }

            // RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not.
            // Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now
            // and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the
            // .NET HttpRequestMessage and Content header collections.
            rtContent.Headers.ContentLength = null;

            // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
            // Desktop System.Net allows both headers to be specified but ends up stripping out
            // 'Content-Length' and using chunked semantics.  The WinRT APIs throw an exception so
            // we need to manually strip out the conflicting header to maintain app compatibility.
            if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value)
            {
                content.Headers.ContentLength = null;
            }
            else
            {
                // Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding
                content.Headers.ContentLength = content.Headers.ContentLength;
            }

            foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers)
            {
                foreach (string value in headerPair.Value)
                {
                    if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value))
                    {
                        // rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers 
                        // will allow custom headers.  If something is not successfully added to the content headers, try adding them to the standard headers.
                        bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value);
                        Debug.Assert(success);
                    }
                }
            }
            return rtContent;
        }
Exemple #7
0
        private static async Task <RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, RTHttpRequestHeaderCollection rtHeaderCollection)
        {
            HttpContent content = request.Content;

            RTIHttpContent      rtContent;
            ArraySegment <byte> buffer;

            // If we are buffered already, it is more efficient to send the data directly using the buffer with the
            // WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by
            // a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter.
            Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false);

            if (contentStream is RTIInputStream)
            {
                rtContent = new RTHttpStreamContent((RTIInputStream)contentStream);
            }
            else if (contentStream is MemoryStream)
            {
                var memStream = contentStream as MemoryStream;
                if (memStream.TryGetBuffer(out buffer))
                {
                    rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count);
                }
                else
                {
                    byte[] byteArray = memStream.ToArray();
                    rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint)byteArray.Length);
                }
            }
            else
            {
                rtContent = new RTHttpStreamContent(contentStream.AsInputStream());
            }

            // RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not.
            // Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now
            // and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the
            // .NET HttpRequestMessage and Content header collections.
            rtContent.Headers.ContentLength = null;

            // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
            // Desktop System.Net allows both headers to be specified but ends up stripping out
            // 'Content-Length' and using chunked semantics.  The WinRT APIs throw an exception so
            // we need to manually strip out the conflicting header to maintain app compatibility.
            if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value)
            {
                content.Headers.ContentLength = null;
            }
            else
            {
                // Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding
                content.Headers.ContentLength = content.Headers.ContentLength;
            }

            foreach (KeyValuePair <string, IEnumerable <string> > headerPair in content.Headers)
            {
                foreach (string value in headerPair.Value)
                {
                    if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value))
                    {
                        // rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers
                        // will allow custom headers.  If something is not successfully added to the content headers, try adding them to the standard headers.
                        bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value);
                        Debug.Assert(success);
                    }
                }
            }
            return(rtContent);
        }