Ejemplo n.º 1
0
        public Task <TResponse> SendAsync <TResponse>(HttpMethod httpMethod, string absoluteUrl, object request,
                                                      CancellationToken token = new CancellationToken())
        {
            if (!httpMethod.HasRequestBody() && request != null)
            {
                var queryString = QueryStringSerializer.SerializeObject(request);
                if (!string.IsNullOrEmpty(queryString))
                {
                    absoluteUrl += "?" + queryString;
                }
            }

            var client      = GetHttpClient();
            var httpRequest = new HttpRequestMessage(httpMethod, absoluteUrl);

            httpRequest.Headers.Add(HeaderNames.Accept, Accept);
            httpRequest.Headers.Add(HeaderNames.UserAgent, DefaultUserAgent);
            if (EnableCompression)
            {
                httpRequest.Headers.Add(HeaderNames.AcceptEncoding, "gzip");
            }

            if (httpMethod.HasRequestBody() && request != null)
            {
                var httpContent = request as HttpContent;
                if (httpContent != null)
                {
                    httpRequest.Content = httpContent;
                }
                else
                {
                    var str    = request as string;
                    var bytes  = request as byte[];
                    var stream = request as Stream;

                    if (str != null)
                    {
                        httpRequest.Content = new StringContent(str, Encoding.UTF8, ContentType);
                    }
                    else if (bytes != null)
                    {
                        httpRequest.Content = new ByteArrayContent(bytes);
                        httpRequest.Content.Headers.Add(HeaderNames.ContentType, ContentType);
                    }
                    else if (stream != null)
                    {
                        httpRequest.Content = new StreamContent(stream);
                        httpRequest.Content.Headers.Add(HeaderNames.ContentType, ContentType);
                    }
                    else
                    {
                        if (ContentType == MimeTypes.Json)
                        {
                            httpRequest.Content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8,
                                                                    ContentType);
                        }
                        else if (ContentType == MimeTypes.FormUrlEncoded)
                        {
                            var s        = QueryStringSerializer.SerializeObject(request);
                            var contents = new List <KeyValuePair <string, string> >();

                            foreach (var pair in QueryHelpers.ParseQuery(s))
                            {
                                var keyValue = new KeyValuePair <string, string>(pair.Key, pair.Value);
                                contents.Add(keyValue);
                            }
                            httpRequest.Content = new FormUrlEncodedContent(contents);
                        }
                    }
                }
            }

            ApplyWebRequestFilters(httpRequest);

            Interlocked.Increment(ref _activeAsyncRequests);

            if (token == default(CancellationToken))
            {
                if (CancelTokenSource == null)
                {
                    CancelTokenSource = new CancellationTokenSource();
                }
                token = CancelTokenSource.Token;
            }

            var sendAsyncTask = client.SendAsync(httpRequest, token);

            if (typeof(TResponse) == typeof(HttpResponseMessage))
            {
                return((Task <TResponse>)(object) sendAsyncTask);
            }

            return(sendAsyncTask.ContinueWith(responseTask =>
            {
                var httpRes = responseTask.Result;

                if (!httpRes.IsSuccessStatusCode)
                {
                    ThrowIfError(httpRes);
                }

                if (typeof(TResponse) == typeof(string))
                {
                    return httpRes.Content.ReadAsStringAsync()
                    .ContinueWith(task => (TResponse)(object)task.Result, token);
                }

                if (typeof(TResponse) == typeof(byte[]))
                {
                    return httpRes.Content.ReadAsByteArrayAsync()
                    .ContinueWith(task => (TResponse)(object)task.Result, token);
                }

                if (typeof(TResponse) == typeof(Stream))
                {
                    return httpRes.Content.ReadAsStreamAsync()
                    .ContinueWith(task => (TResponse)(object)task.Result, token);
                }

                return httpRes.Content.ReadAsStringAsync().ContinueWith(task =>
                {
                    var body = task.Result;
                    var response = body.AsJson <TResponse>();
                    return response;
                }, token);
            }, token).Unwrap());
        }