Пример #1
0
        public TwitterAuthorizationToken RequestToken()
        {
            const string grantType = "grant_type=client_credentials";

            var content = new StringContent(grantType);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

            var param = new HttpParameters
            {
                BaseUrl = _baseUrl,
                AuthorizationHeader = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(
                Encoding.ASCII.GetBytes(
                    string.Format("{0}:{1}", Uri.EscapeDataString(_oauthConsumerKey),
                                  Uri.EscapeDataString(_oauthConsumerSecret))))),
                Content = content,
                DefaultHeaders = new Dictionary<string, string> { { "Accept-Encoding", "gzip" }, { "Host", "api.twitter.com" } },
                ResourceUrl = "oauth2/token"
            };

            var rawJWt = _httpClient.Post(param);
            var   token = JsonConvert.DeserializeObject<TwitterAuthorizationToken>(rawJWt);

            if (!token.TokenType.Equals(TokenType, StringComparison.CurrentCultureIgnoreCase))
            {
                return null;
            }

            return token;
        }
        public string Post(HttpParameters param)
        {
            if (string.IsNullOrEmpty(param.BaseUrl))
            {
                throw new ArgumentNullException("BaseUrl is required");
            }
            var client = new HttpClient{BaseAddress = new Uri(param.BaseUrl)};
            if (param.AuthorizationHeader != null)
            {
                client.DefaultRequestHeaders.Authorization = param.AuthorizationHeader;
            }

            if (param.DefaultHeaders != null)
            {
                foreach (var header in param.DefaultHeaders)
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                }
            }
            //if (param.Content == null)
            //{
            //    throw new InvalidOperationException("Http content most be provided");
            //}

            HttpResponseMessage response;
            try
            {
                response = client.PostAsync(param.ResourceUrl, param.Content).Result;
                response.EnsureSuccessStatusCode();
            }
            catch (HttpRequestException ex)
            {
                throw;
            }
            catch (WebException ex)
            {
                throw;
            }
            catch (TaskCanceledException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                client.Dispose();
            }

            string apiResponse;
            using (var responseStream = response.Content.ReadAsStreamAsync())
            using (var decompressedStream = new GZipStream(responseStream.Result, CompressionMode.Decompress))
            using (var streamReader = new StreamReader(decompressedStream))
            {
                var rawResponse = streamReader.ReadToEnd();
                apiResponse = JsonConvert.DeserializeObject(rawResponse).ToString();
            }

            return apiResponse;
        }
        public string Get(HttpParameters param)
        {
            if (string.IsNullOrEmpty(param.BaseUrl))
            {
                throw new ArgumentNullException("BaseUrl is required");
            }
            var client = new HttpClient { BaseAddress = new Uri(param.BaseUrl) };

            if (param.AuthorizationHeader != null)
            {
                client.DefaultRequestHeaders.Authorization = param.AuthorizationHeader;
            }
            if (param.DefaultHeaders.Any())
            {
                foreach (var header in param.DefaultHeaders)
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            string result;

            try
            {
                var requestTask = client.GetAsync(param.ResourceUrl);
                HttpResponseMessage apiResponse = requestTask.Result;
                apiResponse.EnsureSuccessStatusCode();

                using (var responseStream = apiResponse.Content.ReadAsStreamAsync())
                using (
                    var decompressedStream = new GZipStream(responseStream.Result,
                                                            CompressionMode.Decompress))
                using (var streamReader = new StreamReader(decompressedStream))
                {
                    var rawContent = streamReader.ReadToEnd();
                    result = JsonConvert.DeserializeObject(rawContent).ToString();
                }

            }
            catch (HttpRequestException ex)
            {
                throw;
            }
            catch (WebException ex)
            {
                throw;
            }
            catch (TaskCanceledException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                client.Dispose();
            }
            return result;
        }