/// <summary>
 /// Sends the request and automatically waits/retries if the response is <see cref="Windows.Web.Http.HttpStatusCode.ServiceUnavailable"/>.
 /// </summary>
 /// <param name="request">The <see cref="Windows.Web.Http.HttpRequestMessage"/> to send.</param>
 /// <returns>A <see cref="System.Threading.Tasks.Task{T}"/> whose result is the <see cref="Windows.Web.Http.HttpResponseMessage"/> from the server.</returns>
 public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
 {
     return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
     {
         HttpResponseMessage result = null;
         int retries = 0;
         while (retries < _MaxRetries || retries == 0)
         {
             result = await _InnerFilter.SendRequestAsync(request).AsTask().ConfigureAwait(false);
             if (ShouldRetry(result))
             {
                 if (await WaitIfNotTooLong(result.Headers.RetryAfter).ConfigureAwait(false))
                 {
                     retries++;
                 }
                 else
                 {
                     break;
                 }
             }
             else
             {
                 break;
             }
         }
         return result;
     }));
 }
Exemplo n.º 2
0
        /// <summary>
        /// Passes on the request to the inner handler when there are less than the maximum number of concurrent requests, otherwise waits for the number of concurrent requests to drop below the maximum and then passes the request on.
        /// </summary>
        /// <param name="request">The request to pass on.</param>
        /// <returns>An asynchronous operation whose result is a <see cref="HttpResponseMessage"/>.</returns>
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
            {
                var semaphore = _ThrottlingSemaphore;
                if (semaphore == null)
                {
                    throw new ObjectDisposedException(nameof(ThrottledConcurrentRequestHandler));
                }

                while (!semaphore.WaitOne(250))
                {
                    cancellationToken.ThrowIfCancellationRequested();
                }

                try
                {
                    return await _InnerHandler.SendRequestAsync(request).AsTask().ConfigureAwait(false);
                }
                finally
                {
                    try
                    {
                        //If the handler was disposed while the request was inflihght, avoid throwing
                        //the object disposed condition. However, a race condition is still possible
                        //so catch and suppress the exception if it does occur.
                        if (_ThrottlingSemaphore != null)
                        {
                            semaphore.Release();
                        }
                    }
                    catch (ObjectDisposedException) { }
                }
            }));
        }
Exemplo n.º 3
0
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
            {
                HttpResponseMessage response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);
                cancellationToken.ThrowIfCancellationRequested();
                if ((response != null) && (response.Content != null) && (response.Content.Headers != null))
                {
                    if (response.Content.Headers.ContainsKey("Content-Type"))
                    {
                        if ((response.Content.Headers["Content-Type"].StartsWith("text/xml")) ||
                            (response.Content.Headers["Content-Type"].StartsWith("application/vnd.ms-sstr+xml")))
                        {
                            // Read and update manifest
                            // Put Video Stream Index at the beginning of the manifest
                            // Store the information related to subtitle
                            string manifest = await response.Content.ReadAsStringAsync();
                            string newManifest = UpdateManifest(manifest);
                            if (!string.IsNullOrEmpty(newManifest))
                            {
                                response.Content = new Windows.Web.Http.HttpStringContent(newManifest);
                            }

                            response.Content.Headers["Content-Type"] = "application/vnd.ms-sstr+xml";
                        }
                    }
                }
                return response;
            }));
        }
Exemplo n.º 4
0
            public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
            {
                return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) => {
                    Uri requestUri = request.RequestUri;

                    HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                    HttpCookieCollection cookieCollection = filter.CookieManager.GetCookies(requestUri);

                    //string text = cookieCollection.Count + " cookies found.\r\n";
                    foreach (HttpCookie cookie in cookieCollection)
                    {
                        //text += "--------------------\r\n";
                        //text += "Name: " + cookie.Name + "\r\n";
                        //text += "Domain: " + cookie.Domain + "\r\n";
                        //text += "Path: " + cookie.Path + "\r\n";
                        //text += "Value: " + cookie.Value + "\r\n";
                        //text += "Expires: " + cookie.Expires + "\r\n";
                        //text += "Secure: " + cookie.Secure + "\r\n";
                        //text += "HttpOnly: " + cookie.HttpOnly + "\r\n";
                        if (cookie.Name == "X-CSRF-Token")
                        {
                            request.Headers.Add(cookie.Name, cookie.Value);
                            Debug.WriteLine("csrf token added");
                        }
                    }
                    //Debug.WriteLine(text);
                    //request.Headers.Add("Custom-Header", "CustomRequestValue");
                    HttpResponseMessage response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);
                    cancellationToken.ThrowIfCancellationRequested();
                    //response.Headers.Add("Custom-Header", "CustomResponseValue");
                    return response;
                }));
            }
Exemplo n.º 5
0
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            bool isKeyRequest = String.Equals(request.RequestUri.Host, KeyHost, StringComparison.OrdinalIgnoreCase);

            if (isKeyRequest && AuthorizationHeader != null)
            {
                request.Headers.Authorization = AuthorizationHeader;
            }

            return(innerFilter.SendRequestAsync(request));
        }
        /// <summary>
        /// Compresses the content if suitable, sets the content encoding header and passes on the request to the next handler in the pipeline.
        /// </summary>
        /// <param name="request">The <see cref="Windows.Web.Http.HttpRequestMessage"/> to send.</param>
        /// <returns>A <see cref="System.Threading.Tasks.Task{T}"/> whose result is the <see cref="Windows.Web.Http.HttpResponseMessage"/> from the server.</returns>
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
            {
                if (ShouldCompress(request))
                {
                    request.Content = await GetCompressedContent(request.Content).ConfigureAwait(false);
                }

                return await _InnerFilter.SendRequestAsync(request).AsTask().ConfigureAwait(false);
            }));
        }
Exemplo n.º 7
0
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
            {
                //request.Headers.Add("Token", GoogleModel.Token.access_token);
                HttpResponseMessage response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);

                cancellationToken.ThrowIfCancellationRequested();

                response.Headers.Add("Custom-Header", "CustomResponseValue");
                return response;
            }));
        }
Exemplo n.º 8
0
 //在SendRequertAsync方法里添加自定义的HTTP头
 public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
 {
     return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
     {
         request.Headers.Add("Custom-Header", "CustomRequestValue");
         HttpResponseMessage response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);
         HttpMediaTypeHeaderValue contentType = response.Content.Headers.ContentType;
         if (string.IsNullOrEmpty(contentType.CharSet))
         {
             contentType.CharSet = "UTF-8";
         }
         cancellationToken.ThrowIfCancellationRequested();
         response.Headers.Add("Custom-Header", "CustomResponseValue");
         return response;
     }));
 }
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
            {
                // Get the auth token
                if (null == _token)
                {
                    await AuthenticateAsync();
                }
                request.Headers.Add("Authorization", "OAuth " + _token);
                var response = await _innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);

                cancellationToken.ThrowIfCancellationRequested();
                return response;
            }));
        }
Exemplo n.º 10
0
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
            {
                cancellationToken = this.cancellationToken;

                exe.SetAuthorizationHeader(HttpMethod.Get, url, parameters, request);
                request.Headers.Add("User-Agent", exe.UserAgent);
                request.Headers.Add("Expect", "100-continue");
                request.Headers.Add("Accept-Encoding", "gzip");

                cancellationToken.ThrowIfCancellationRequested();

                return await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);
            }));
        }
Exemplo n.º 11
0
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request) =>
        AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) =>
        {
            cancellationToken.ThrowIfCancellationRequested();

            var uri = request.RequestUri;

            var filter           = new HttpBaseProtocolFilter();
            var cookieCollection = filter.CookieManager.GetCookies(uri);

            var csrf = cookieCollection.FirstOrDefault(cookie => cookie.Name == "X-CSRF-Token");
            if (csrf != null)
            {
                request.Headers.Add(csrf.Name, csrf.Value);
            }

            var response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);

            Debug.WriteLine(
                $"Sent request: {request.Method.Method} {uri}, with data: {(request.Content == null ? "null" : await request.Content.ReadAsStringAsync())}, with headers: {request.Headers.SerializeJson()}");

            return(response);
        });
Exemplo n.º 12
0
            public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
            {
                return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, progress) => {
                    Uri requestUri = request.RequestUri;

                    HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                    HttpCookieCollection cookieCollection = filter.CookieManager.GetCookies(requestUri);

                    var csrf = cookieCollection.FirstOrDefault(cookie => cookie.Name == "X-CSRF-Token");
                    if (csrf != null)
                    {
                        request.Headers.Add(csrf.Name, csrf.Value);
                        Debug.Write("csrf token added");
                    }


                    //Debug.WriteLine(text);
                    //request.Headers.Add("Custom-Header", "CustomRequestValue");
                    HttpResponseMessage response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);
                    cancellationToken.ThrowIfCancellationRequested();
                    //response.Headers.Add("Custom-Header", "CustomResponseValue");
                    return response;
                }));
            }
        public IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
        {
            timeToResponseComplete.Start();
            logView.Log($"{{\"FILTER SendRequestAsync\":{{\"requestUri\":\"{request.RequestUri}\"}}}}", LogViewLoggingLevel.Verbose);

            return(AsyncInfo.Run <HttpResponseMessage, HttpProgress>(async(cancellationToken, operationProgressReporter) =>
            {
                IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> innerOperation = innerFilter.SendRequestAsync(request);

                innerOperation.Progress += new AsyncOperationProgressHandler <HttpResponseMessage, HttpProgress>(
                    (IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> asyncInfo, HttpProgress httpProgressInfo) =>
                {
                    logView.Log($"{{\"FILTER Progress Handler\": {{\"requestUri\":\"{request.RequestUri}\", {httpProgressInfo.ToJsonObject()}}}}}", LogViewLoggingLevel.Verbose);
                });

                HttpResponseMessage response = await innerOperation.AsTask(cancellationToken, operationProgressReporter);
                cancellationToken.ThrowIfCancellationRequested();
                // At this point, SendRequest has completed and we have a response.
                timeToResponseComplete.Stop();

                // We could inspect the content of the response headers:
                var countHeaders = response.Headers.Count();
                logView.Log($"{{\"FILTER Response Complete\": {{\"StatusCode\":\"{response.StatusCode}\",\"timeToResponseComplete\":\"{timeToResponseComplete.ElapsedMilliseconds}\",\"requestUri\":\"{request.RequestUri}\",\"countHeaders\":\"{countHeaders}\"}}}}", LogViewLoggingLevel.Verbose);

                if (!response.IsSuccessStatusCode)
                {
                    logView.Log($"{{\"FILTER Response Failed\": {{\"StatusCode\":\"{response.StatusCode}\",\"timeToResponseComplete\":\"{timeToResponseComplete.ElapsedMilliseconds}\",\"requestUri\":\"{request.RequestUri}\",\"countHeaders\":\"{countHeaders}\"}}}}", LogViewLoggingLevel.Error);
                }

                // Note that we should NOT attempt to access the response.Content in an IHttpFilter such as this,
                // the Content stream is for the base filter and AdaptiveMediaSource to use.
                //
                // If you want to download content in the App and then pass it to the AdaptiveMediaSource,
                // see AppDownloadedKeyRequest in Scenario3, which uses Deferral objects to manage thread timing
                // with the AdaptiveMediaSource.
                return response;
            }));
        }