コード例 #1
0
        /// <summary>
        /// performs the http request and returns the result
        /// </summary>
        /// <param name="request">an instance of IRequest implementation</param>
        /// <param name="token">a cancellation token that can be used by other objects or threads to receive notice of cancellation</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="IOException"></exception>
        /// <exception cref="InvalidRequestException"></exception>
        /// <exception cref="InvalidTokenException"></exception>
        /// <exception cref="InsufficientScopeException"></exception>
        public async Task <HttpServerResponse> GetResponseAsync(IRequest request, CancellationToken token)
        {
            if (null == _httpClient)
            {
                throw new InvalidOperationException("HttpClient is either disposed or was not created successfully.");
            }

            if (null == request)
            {
                throw new ArgumentNullException("request", "Request is required.");
            }

            var prms = request.RequestParams ?? new Dictionary <string, string>();

            _httpClient.DefaultRequestHeaders.Authorization =
                (_authenticator != null && !string.IsNullOrEmpty(_authenticator.Token))
                ? new AuthenticationHeaderValue(_authenticator.AuthenticationScheme, _authenticator.Token)
                : null;

            HttpContent content = new FormUrlEncodedContent(prms);

            content.Headers.ContentType = new MediaTypeHeaderValue(DefaultContentType);

            var response = request.RequestMethod == HttpMethod.Post
                        ? await _httpClient.PostAsync(_hostProvider.BuildUri(request.RelativeUri), content, token)
                        : await _httpClient.GetAsync(_hostProvider.BuildUri(request.RelativeUri) + "?" + prms.ToQueryString(), token);

            if (response == null)
            {
                throw new IOException("Unable to get response from server.");
            }

            // according to yandex API 2xx and 3xx are successful codes.
            if ((int)response.StatusCode < 400)
            {
                return(new HttpServerResponse
                {
                    Status = response.StatusCode,
                    Headers = response.Headers,
                    Stream = await response.Content.ReadAsStreamAsync(),
                });
            }

            if (response.Headers == null || response.Headers.WwwAuthenticate == null)
            {
                return(null);
            }

            var responseError = "Error response received from server, status code " + response.StatusCode;

            var authenticationHeaderValue = response
                                            .Headers
                                            .WwwAuthenticate
                                            .FirstOrDefault(x => x.Scheme == _authenticator.AuthenticationScheme);

            if (authenticationHeaderValue != null)
            {
                responseError = authenticationHeaderValue.Parameter;
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.BadRequest:
                throw new InvalidRequestException(responseError);

            case HttpStatusCode.Unauthorized:
                throw new InvalidTokenException(responseError);

            case HttpStatusCode.Forbidden:
                throw new InsufficientScopeException(responseError);

            default:
                throw new IOException(responseError);
            }
        }
コード例 #2
0
        /// <summary>
        /// performs the http request and returns the result
        /// </summary>
        /// <param name="request">an instance of IRequest implementation</param>
        /// <param name="token">a cancellation token that can be used by other objects or threads to receive notice of cancellation</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="IOException"></exception>
        /// <exception cref="InvalidRequestException"></exception>
        /// <exception cref="InvalidTokenException"></exception>
        /// <exception cref="InsufficientScopeException"></exception>
        public async Task <Stream> UploadDataAsync(IRequest request, CancellationToken token)
        {
            if (_httpClient == null || request == null)
            {
                throw new ArgumentNullException();
            }

            var prms = new Dictionary <string, string>();

            request.AppendItemsTo(prms);

            _httpClient.DefaultRequestHeaders.Authorization =
                (_authenticator != null && !String.IsNullOrEmpty(_authenticator.Token))
                ? new AuthenticationHeaderValue(_authenticator.AuthenticationScheme, _authenticator.Token)
                : null;

            HttpContent content = new FormUrlEncodedContent(prms.Select(x => new KeyValuePair <string, string>(x.Key, x.Value)));

            content.Headers.ContentType = new MediaTypeHeaderValue(DefaultContentType);

            var response = await _httpClient.PostAsync(_hostProvider.BuildUri(request.RelativeUri), content, token);

            if (response == null)
            {
                throw new IOException();
            }

            if (response.StatusCode == HttpStatusCode.OK)
            {
                return(await response.Content.ReadAsStreamAsync());
            }

            if (response.Headers == null || response.Headers.WwwAuthenticate == null)
            {
                return(null);
            }

            var responseError = string.Empty;

            var authenticationHeaderValue = response
                                            .Headers
                                            .WwwAuthenticate
                                            .FirstOrDefault(x => x.Scheme == _authenticator.AuthenticationScheme);

            if (authenticationHeaderValue != null)
            {
                responseError = authenticationHeaderValue.Parameter;
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.BadRequest:
                throw new InvalidRequestException(responseError);

            case HttpStatusCode.Unauthorized:
                throw new InvalidTokenException(responseError);

            case HttpStatusCode.Forbidden:
                throw new InsufficientScopeException(responseError);

            default:
                throw new IOException(responseError);
            }
        }