public string Invoke(NetHttpMethod method, string uri, IDictionary <string, string> headers, string body)
        {
            Contract.Requires(null != method);

            var httpMethod = HttpMethod.Get;

            if (NetHttpMethod.Get == method)
            {
                httpMethod = HttpMethod.Get;
            }
            else if (NetHttpMethod.Post == method)
            {
                httpMethod = HttpMethod.Post;
            }
            else if (NetHttpMethod.Put == method)
            {
                httpMethod = HttpMethod.Put;
            }
            else if (NetHttpMethod.Delete == method)
            {
                httpMethod = HttpMethod.Delete;
            }
            else if (NetHttpMethod.Head == method)
            {
                httpMethod = HttpMethod.Head;
            }
            else
            {
                const bool isSupportedHttpMethod = false;
                Contract.Assert(isSupportedHttpMethod);
            }

            return(Invoke(httpMethod, uri, headers, body));
        }
Ejemplo n.º 2
0
        public async Task <HttpResponseMessage> GetHttpResponseAsync(ITwitterQuery twitterQuery, ITwitterClientHandler handler = null)
        {
            using (var client = GetHttpClient(twitterQuery, handler))
            {
                client.Timeout = twitterQuery.Timeout;

                var httpMethod = new HttpMethod(twitterQuery.HttpMethod.ToString());

                if (twitterQuery.HttpContent == null)
                {
                    return(await client.SendAsync(new HttpRequestMessage(httpMethod, twitterQuery.Url)).ConfigureAwait(false));
                }
                else
                {
                    if (httpMethod == HttpMethod.Post)
                    {
                        return(await client.PostAsync(twitterQuery.Url, twitterQuery.HttpContent).ConfigureAwait(false));
                    }

                    if (httpMethod == HttpMethod.Put)
                    {
                        return(await client.PutAsync(twitterQuery.Url, twitterQuery.HttpContent).ConfigureAwait(false));
                    }

                    throw new ArgumentException("Cannot send HttpContent in a WebRequest that is not POST or PUT.");
                }
            }
        }
Ejemplo n.º 3
0
        public async Task <HttpResponseMessage> PatchAsync(HttpClient client, string serviceUrl, HttpContent content)
        {
            var method  = new System.Net.Http.HttpMethod("PATCH");
            var request = new HttpRequestMessage(method, serviceUrl)
            {
                Content = content
            };

            var response = new HttpResponseMessage();

            try
            {
                response = await client.SendAsync(request);
            }
            catch (TaskCanceledException exception)
            {
                _logger.LogError(exception.ToString());
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.ToString());
            }

            response.StatusCode = HttpStatusCode.InternalServerError;
            return(response);
        }
Ejemplo n.º 4
0
 virtual protected async Task <Response> CreateRequest <Response>(
     string url,
     net.HttpMethod method,
     object input,
     string token)
 {
     return(await CreateRequestMessage(url, method, token, async (msg) =>
     {
         if (input is Stream stream)
         {
             using (var content = new net.StreamContent(stream))
             {
                 content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                 msg.Content = content;
                 return await GetResult <Response>(msg);
             }
         }
         else
         {
             using (var content = new net.StringContent(JObject.FromObject(input).ToString()))
             {
                 content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                 msg.Content = content;
                 return await GetResult <Response>(msg);
             }
         }
     }));
 }
Ejemplo n.º 5
0
        private static T MakeRequest <T>(string uri, System.Net.Http.HttpMethod httpMethod, byte[] body, Dictionary <string, string> headers,
                                         string contentType)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            #region set headers
            #endregion

            request.ContentType            = contentType;
            request.Method                 = httpMethod.Method;
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            #region set Body content
            if (body != null)
            {
                request.ContentLength = body.Length;
                using (var requestBody = request.GetRequestStream())
                {
                    requestBody.Write(body, 0, body.Length);
                }
            }
            #endregion


            using (var response = (HttpWebResponse)request.GetResponse())
                using (var stream = response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        return(JsonConvert.DeserializeObject <T>(reader.ReadToEnd()));
                    }
        }
        /// <summary>
        /// Asyn function to create http request to fetch videos from sharepoint site.
        /// </summary>
        /// <param name="httpmethod">http method type</param>
        /// <param name="requesturi">Uri of the sharepoint site along with the library name</param>
        /// <returns></returns>
        public async Task <byte[]> CreateHttpRequest(System.Net.Http.HttpMethod httpmethod, Uri requesturi)
        {
            byte[] responseStream;
            // Populates the list of videos from the sharepoint site .
            var    httpRequestMessage = new HttpRequestMessage(httpmethod, requesturi);
            string contentType        = "application/json;odata=verbose;charset=utf-8";
            var    httpClientHandler  = new HttpClientHandler();
            var    request            = new HttpClient(httpClientHandler);

            httpRequestMessage.Headers.Add("Accept", contentType); // set the content type of the request
            if (httpClientHandler.CookieContainer == null)
            {
                httpClientHandler.CookieContainer = new CookieContainer();
            }

            // get the auth cookies  after authenticating with Microsoft Online Services
            CookieContainer cookieContainer = await
                                              SharePointOnlineLoginHelper.AuthObj.GetCookieContainer();

            foreach (Cookie c in cookieContainer.GetCookies(SharePointOnlineLoginHelper.AuthObj.SiteUrl))
            {
                // append  auth cookies to the request
                httpClientHandler.CookieContainer.Add(SharePointOnlineLoginHelper.AuthObj.SiteUrl, c);
            }

            // Send the request and read the response as an array of bytes
            using (var resultData = await request.SendAsync(httpRequestMessage))
            {
                responseStream = await resultData.Content.ReadAsByteArrayAsync();
            }
            return(responseStream);
        }
Ejemplo n.º 7
0
 public void ТоЗапрашиваемМетодGETВЕС(System.Net.Http.HttpMethod httpMethod, string pathWithQueryParams)
 {
     pathWithQueryParams            = specFlowContextUtils.ResolveExtractorExpression(pathWithQueryParams);
     lastRequestPathWithQueryParams = pathWithQueryParams;
     lastRequestHttpMethod          = httpMethod;
     ProcessSimpleApiResponse(httpClientFixture.SendRequest(httpMethod, pathWithQueryParams));
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UnexpectedRequest"/> class.
        /// </summary>
        /// <param name="method">The request method.</param>
        /// <param name="headers">The request headers.</param>
        /// <param name="requestUri">The request URI.</param>
        /// <param name="content">The request content.</param>
        public UnexpectedRequest(System.Net.Http.HttpMethod method, HttpRequestHeaders headers, Uri requestUri, HttpContent content)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            this.Method  = (HttpMethod)Enum.Parse(typeof(HttpMethod), method.Method);
            this.Headers = new Dictionary <string, IEnumerable <string> >();

            foreach (var httpRequestHeader in headers)
            {
                this.Headers.Add(httpRequestHeader.Key, httpRequestHeader.Value);
            }

            this.RequestUri = requestUri;
            this.Content    = content.ReadAsStringAsync().Result;
        }
        /// <summary>
        /// Performs an asynchronous request that can be cancelled.
        /// </summary>
        /// <param name="request">The options to consider.</param>
        /// <param name="cancel">The token for cancelling the task.</param>
        /// <returns>
        /// The task that will eventually give the response data.
        /// </returns>
        protected override async Task <IResponse> PerformRequestAsync(Request request, CancellationToken cancel)
        {
            // create the request message
            var method         = new HttpMethod(request.Method.Stringify());
            var requestMessage = new HttpRequestMessage(method, request.Address);
            var contentHeaders = new List <KeyValuePair <String, String> >();

            foreach (var header in request.Headers)
            {
                // Source:
                // https://github.com/aspnet/Mvc/blob/02c36a1c4824936682b26b6c133d11bebee822a2/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpRequestMessage/HttpRequestMessageFeature.cs
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value))
                {
                    contentHeaders.Add(new KeyValuePair <String, String>(header.Key, header.Value));
                }
            }

            // set up the content
            if (request.Content != null && method != HttpMethod.Get && method != HttpMethod.Head)
            {
                requestMessage.Content = new StreamContent(request.Content);

                foreach (var header in contentHeaders)
                {
                    requestMessage.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // execute the request
            var responseMessage = await _client.SendAsync(requestMessage, cancel).ConfigureAwait(false);

            // convert the response
            var response = new DefaultResponse
            {
                Headers    = responseMessage.Headers.ToDictionary(p => p.Key, p => String.Join(", ", p.Value)),
                Address    = Url.Convert(responseMessage.RequestMessage.RequestUri),
                StatusCode = responseMessage.StatusCode
            };

            // get the anticipated content
            var content = responseMessage.Content;

            if (content != null)
            {
                response.Content = await content.ReadAsStreamAsync().ConfigureAwait(false);

                foreach (var pair in content.Headers)
                {
                    response.Headers[pair.Key] = String.Join(", ", pair.Value);
                }
            }

            if (IsRedirected(response) && !response.Headers.ContainsKey(HeaderNames.SetCookie))
            {
                response.Headers[HeaderNames.SetCookie] = String.Empty;
            }

            return(response);
        }
Ejemplo n.º 10
0
 private async Task <Response> CreateRequest <Response>(
     string url,
     net.HttpMethod method,
     string token)
 {
     return(await CreateRequestMessage(url, method, token,
                                       async msg => { return await GetResult <Response>(msg); }));
 }
Ejemplo n.º 11
0
 public static HttpResult Request(string url, System.Net.Http.HttpMethod method, Encoding encoding)
 {
     return(Request(new HttpRequest
     {
         Url = url,
         Method = method.ToString(),
         Encoding = encoding
     }));
 }
        /// <inheritdoc />
        public async Task <string> GetJsonResponseAsync <TRequest>(System.Net.Http.HttpMethod httpMethod, string relativeUrl, IEnumerable <string> queryParameters, TRequest body)
        {
            var request = await PrepareRequestAsync(httpMethod, relativeUrl, queryParameters, body).ConfigureAwait(false);

            var response = await HttpClient.SendAsync(request).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();
            return(await GetResponseContentAsync(response).ConfigureAwait(false));
        }
Ejemplo n.º 13
0
        private static Task NoRequestBodySuccessTestAsync(Method method)
        => ExecuteAsync(
            () => new HttpRequestMessage(method, $"200?message={Value}"),
            async(nginxResponse, response) =>
        {
            var expectedContent = method == Method.Head ? string.Empty : Value;

            await EnsureSuccessAsync(nginxResponse, expectedContent);
            await EnsureSuccessAsync(response, expectedContent);
        });
Ejemplo n.º 14
0
 /* Responsible for creating an HTTP request of specified type. Only used
  * during GET and DELETE requests, since you cannot apply a payload to
  * your request.
  */
 async Task <Response <TOut> > CreateEmptyRequest <TOut>(
     string url,
     net.HttpMethod method,
     Dictionary <string, string> headers)
 {
     using (var msg = CreateRequestMessage(method, url, headers))
     {
         return(await GetResult <TOut>(msg));
     }
 }
Ejemplo n.º 15
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var jobj = JObject.Load(reader);
     var url = (string)jobj["url"];
     var method = new System.Net.Http.HttpMethod((string)jobj["method"]);
     var request = new HttpRequestMessage(method, url);
     request.Content = ReadBody(jobj);
     ReadHeaders(jobj, serializer, request.Headers, request.Content);
     return request;
 }
Ejemplo n.º 16
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jobj    = JObject.Load(reader);
            var url     = (string)jobj["url"];
            var method  = new System.Net.Http.HttpMethod((string)jobj["method"]);
            var request = new HttpRequestMessage(method, url);

            request.Content = ReadBody(jobj);
            ReadHeaders(jobj, serializer, request.Headers, request.Content);
            return(request);
        }
Ejemplo n.º 17
0
        // https://compiledexperience.com/blog/posts/patch-support-in-httpclient

        public async static Task <HttpResponseMessage> PatchAsync(HttpClient client, string requestUri, HttpContent content)
        {
            var method = new System.Net.Http.HttpMethod("PATCH");

            var request = new HttpRequestMessage(method, requestUri)
            {
                Content = content
            };

            return(await client.SendAsync(request));
        }
Ejemplo n.º 18
0
        private async Task <RestResponse> ExecuteHttpRequest(System.Net.Http.HttpMethod method, Uri url, RestRequest request)
        {
            var requestMessage = BuildRequestMessage(method, url, request);

            using (var cts = new CancellationTokenSource(_timeout))
            {
                HttpResponseMessage response = await _client.SendAsync(requestMessage, cts.Token);

                return(await RestResponse.FromResponseMessage(response));
            }
        }
Ejemplo n.º 19
0
 private static Task WithRequestBodySuccessTestAsync(Method method)
 => ExecuteAsync(
     () => new HttpRequestMessage(method, "b200")
 {
     Content = JsonContent.Create(Value)
 },
     async(nginxResponse, response) =>
 {
     await EnsureSuccessAsync(nginxResponse);
     await EnsureSuccessAsync(response);
 });
Ejemplo n.º 20
0
 private Result <TResponse> Send <TResponse>(HttpMethod method,
                                             string relativeUrl, string contentType, string accept,
                                             Action <Stream> writer, Func <Stream, TResponse> reader,
                                             IDictionary <string, string> cookies       = null,
                                             Action <HttpRequestHeaders> requestHeaders = null,
                                             Action <HttpContentHeaders> contentHeaders = null,
                                             string filename = null) where TResponse : class
 {
     return(Execute(method, relativeUrl, contentType, accept, reader, writer,
                    cookies, filename, requestHeaders, contentHeaders));
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Creates a minimal <see cref="ApiRequest"/> having the passed method and url.
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static ApiRequest Create(System.Net.Http.HttpMethod method, string url)
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage();

            requestMessage.RequestUri = new Uri(url);
            requestMessage.Method     = method;

            ApiRequest apiRequest = new ApiRequest();

            apiRequest.RequestMessage = requestMessage;
            return(apiRequest);
        }
Ejemplo n.º 22
0
        protected HttpWebRequest CreateJsonRequest(string url, System.Net.Http.HttpMethod method, params Cookie[] cookies)
        {
            var newRequest = (HttpWebRequest)WebRequest.Create(url);

            newRequest.ContentType     = "application/json";
            newRequest.Method          = method.Method;
            newRequest.CookieContainer = new CookieContainer();
            foreach (var cookie in cookies)
            {
                newRequest.CookieContainer.Add(cookie);
            }
            return(newRequest);
        }
Ejemplo n.º 23
0
        private static Task NoRequestBodyFailTestAsync(Method method)
        => ExecuteAsync(
            () => new HttpRequestMessage(method, $"500?message={Value}"),
            async(nginxResponse, response) =>
        {
            var expectedContent = method == Method.Head ? string.Empty : Value;

            nginxResponse.IsSuccessStatusCode.Should().BeFalse();
            (await nginxResponse.Content.ReadAsStringAsync()).Should().Be(expectedContent);

            response.IsSuccessStatusCode.Should().BeFalse();
            (await response.Content.ReadAsStringAsync()).Should().Be(expectedContent);
        });
Ejemplo n.º 24
0
 /// <summary>
 /// <para>Asserts that a given HTTP call was sent with expected parameters.</para>
 /// </summary>
 /// <param name="httpMethod">Expected HTTP method type.</param>
 /// <param name="localPath">Expected local part of the called Uri.</param>
 public void AssertHttpCall(System.Net.Http.HttpMethod httpMethod, string localPath)
 {
     HandlerMock.Protected().Verify(
         "SendAsync",
         Times.Exactly(1),
         ItExpr.Is <HttpRequestMessage>(req =>
                                        req.Method == httpMethod &&
                                        req.RequestUri.LocalPath == $"/v1_1/{cloudName}/{localPath}" &&
                                        req.Properties.Count == 0
                                        ),
         ItExpr.IsAny <CancellationToken>()
         );
 }
Ejemplo n.º 25
0
 public Task <HttpResponseMessage> Request(Method method, Uri url, Dictionary <string, object> options)
 {
     if (method == HttpMethod.Get && options.Count == 0)
     {
         return(Request(method, url));
     }
     else
     {
         var json = JsonConvert.SerializeObject(options);
         var body = new StringContent(json, Encoding.UTF8, "application/json");
         return(Request(method, url, body));
     }
 }
Ejemplo n.º 26
0
        private async Task <StreamReader> GetStreamReader(HttpClient client, ITwitterQuery twitterQuery)
        {
            try
            {
                var uri             = new Uri(twitterQuery.QueryURL);
                var endpoint        = uri.GetEndpointURL();
                var queryParameters = uri.Query.Remove(0, 1);
                var httpMethod      = new HttpMethod(twitterQuery.HttpMethod.ToString());

                HttpRequestMessage request;

                if (httpMethod == HttpMethod.Post)
                {
                    request = new HttpRequestMessage(httpMethod, endpoint)
                    {
                        Content = new StringContent(queryParameters, Encoding.UTF8, "application/x-www-form-urlencoded")
                    };
                }
                else
                {
                    request = new HttpRequestMessage(httpMethod, twitterQuery.QueryURL);
                }


                var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

                _currentResponseHttpStatusCode = (int)response.StatusCode;
                var body = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                return(new StreamReader(body, Encoding.GetEncoding("utf-8")));
            }
            catch (WebException wex)
            {
                client.Dispose();
                HandleWebException(wex);
            }
            catch (Exception ex)
            {
                client.Dispose();

                if (ex is AggregateException && ex.InnerException is WebException)
                {
                    HandleWebException(ex.InnerException as WebException);
                }

                _lastException = ex;
                SetStreamState(StreamState.Stop);
            }

            return(null);
        }
Ejemplo n.º 27
0
        private static Task WithRequestBodyFailTestAsync(Method method)
        => ExecuteAsync(
            () => new HttpRequestMessage(method, "b500")
        {
            Content = JsonContent.Create(Value)
        },
            async(nginxResponse, response) =>
        {
            nginxResponse.IsSuccessStatusCode.Should().BeFalse();
            (await nginxResponse.Content.ReadAsStringAsync()).Should().Be(Value);

            response.IsSuccessStatusCode.Should().BeFalse();
            (await response.Content.ReadAsStringAsync()).Should().Be(Value);
        });
Ejemplo n.º 28
0
        public SimpleApiResponse SendRequest(System.Net.Http.HttpMethod httpMethod, string path)
        {
            var request = new HttpRequestMessage(httpMethod, BuildScenarioUri(path));

            ConfigureScenarioHeaders(request);
            var response = httpClient.SendAsync(request).GetAwaiter().GetResult();

            return(new SimpleApiResponse()
            {
                StatusCode = response.StatusCode,
                IsSuccess = response.IsSuccessStatusCode,
                Headers = response.Headers,
                StringContent = response.Content == null ? default : response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
            });
Ejemplo n.º 29
0
        public void Intercept(System.Net.Http.HttpMethod method, Uri uri, Func <System.Net.Http.HttpRequestMessage, System.Net.Http.HttpResponseMessage> intercepter)
        {
            if (uri == null)
            {
                uri = this.BaseAddress;
            }

            if (!uri.IsAbsoluteUri)
            {
                uri = new Uri(this.BaseAddress, uri);
            }

            this.handler.Intercept(method, uri, intercepter);
        }
Ejemplo n.º 30
0
        private async Task <TResponce> SendRequestExt <TResponce>(HttpClient client, System.Net.Http.HttpMethod method, string url, HttpContent content, List <JsonConverter> jsonConverters)
        {
            using (var message = new HttpRequestMessage(method, url)
            {
                Content = content
            })
                using (var response = await client.SendAsync(message))
                {
                    EnsureSuccessStatusCodeCustom(response);
                    var body = await response.Content.ReadAsStringAsync();

                    var result = JsonConvert.DeserializeObject <TResponce>(body, jsonConverters.ToArray());
                    return(result);
                }
        }
        public async Task<IResponse> RequestAsync(IRequest request, CancellationToken cancellationToken)
        {
            // create the request message
            var method = new HttpMethod(request.Method.ToString().ToUpper());
            var requestMessage = new HttpRequestMessage(method, request.Address);
            var contentHeaders = new List<KeyValuePair<string, string>>();
            foreach (var header in request.Headers)
            {
                // Source:
                // https://github.com/aspnet/Mvc/blob/02c36a1c4824936682b26b6c133d11bebee822a2/src/Microsoft.AspNet.Mvc.WebApiCompatShim/HttpRequestMessage/HttpRequestMessageFeature.cs
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value))
                {
                    contentHeaders.Add(new KeyValuePair<string, string>(header.Key, header.Value));
                }
            }

            // set up the content
            if (request.Content != null && method != HttpMethod.Get && method != HttpMethod.Head)
            {
                requestMessage.Content = new StreamContent(request.Content);
                foreach (var header in contentHeaders)
                {
                    requestMessage.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // execute the request
            var responseMessage = await _client.SendAsync(requestMessage, cancellationToken);

            // convert the response
            var response = new Response
            {
                Headers = responseMessage.Headers.ToDictionary(p => p.Key, p => string.Join(", ", p.Value)),
                Address = Url.Convert(responseMessage.RequestMessage.RequestUri),
                StatusCode = responseMessage.StatusCode
            };

            if (responseMessage.Content != null)
            {
                response.Content = await responseMessage.Content.ReadAsStreamAsync();
                foreach (var pair in responseMessage.Content.Headers)
                {
                    response.Headers[pair.Key] = string.Join(", ", pair.Value);
                }
            }

            return response;
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Prepares a request by calculating the proper url.
        /// </summary>
        /// <typeparam name="TRequest">The object to serialize into the body.</typeparam>
        /// <param name="relativeUrl">The relative url.</param>
        /// <param name="httpMethod">The <see cref="HttpMethod"/>.</param>
        /// <param name="body">The request's body.</param>
        /// <param name="queryParameters">The query parameters.</param>
        /// <returns></returns>
        protected async Task <HttpRequestMessage> PrepareRequestAsync <TRequest>(System.Net.Http.HttpMethod httpMethod, string relativeUrl, IEnumerable <string> queryParameters, TRequest body)
        {
            var url = queryParameters == null
                ? relativeUrl
                : relativeUrl + BuildQueryParameterString(queryParameters);
            var request = new HttpRequestMessage(httpMethod, url);

            if (body != null)
            {
                var json = await Task.Run(() => JsonConvert.SerializeObject(body)).ConfigureAwait(false);

                request.Content = new StringContent(json, Encoding.UTF8, "application/json");
            }

            return(request);
        }
Ejemplo n.º 33
0
        public async Task<HttpResponseMessage> GetHttpResponse(ITwitterQuery twitterQuery, ITwitterClientHandler handler = null)
        {
            using (var client = GetHttpClient(twitterQuery, handler))
            {
                client.Timeout = twitterQuery.Timeout;

                var httpMethod = new HttpMethod(twitterQuery.HttpMethod.ToString());

                if (twitterQuery.HttpContent == null)
                {
                    return await client.SendAsync(new HttpRequestMessage(httpMethod, twitterQuery.QueryURL)).ConfigureAwait(false);
                }
                else
                {
                    if (httpMethod != HttpMethod.Post)
                    {
                        throw new ArgumentException("Cannot send HttpContent in a WebRequest that is not POST.");
                    }

                    return await client.PostAsync(twitterQuery.QueryURL, twitterQuery.HttpContent).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 34
0
        private async Task<StreamReader> GetStreamReader(HttpClient client, ITwitterQuery twitterQuery)
        {
            try
            {
                var uri = new Uri(twitterQuery.QueryURL);
                var endpoint = uri.GetEndpointURL();
                var queryParameters = uri.Query.Remove(0, 1);
                var httpMethod = new HttpMethod(twitterQuery.HttpMethod.ToString());

                HttpRequestMessage request;

                if (httpMethod == HttpMethod.Post)
                {
                    request = new HttpRequestMessage(httpMethod, endpoint)
                    {
                        Content = new StringContent(queryParameters, Encoding.UTF8, "application/x-www-form-urlencoded")
                    };
                }
                else
                {
                    request = new HttpRequestMessage(httpMethod, twitterQuery.QueryURL);
                }


                var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
                var body = await response.Content.ReadAsStreamAsync();

                return new StreamReader(body, Encoding.GetEncoding("utf-8"));
            }
            catch (WebException wex)
            {
                client.Dispose();
                HandleWebException(wex);
            }
            catch (Exception ex)
            {
                client.Dispose();

                if (ex is AggregateException && ex.InnerException is WebException)
                {
                    HandleWebException(ex.InnerException as WebException);
                }

                _lastException = ex;
                SetStreamState(StreamState.Stop);
            }

            return null;
        }