Example #1
0
        private async Task <HttpResponseMessage> PrivateMakeRequestAsync(
            TimeSpan timeout,
            HttpCompletionOption completionOption,
            HttpMethod method,
            string path,
            IQueryString queryString,
            IDictionary <string, string> headers,
            IRequestContent data,
            CancellationToken cancellationToken)
        {
            // If there is a timeout, we turn it into a cancellation token. At the same time, we need to link to the caller's
            // cancellation token. To avoid leaking objects, we must then also dispose of the CancellationTokenSource. To keep
            // code flow simple, we treat it as re-entering the same method with a different CancellationToken and no timeout.
            if (timeout != s_InfiniteTimeout)
            {
                using (var timeoutTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
                {
                    timeoutTokenSource.CancelAfter(timeout);

                    // We must await here because we need to dispose of the CTS only after the work has been completed.
                    return(await PrivateMakeRequestAsync(s_InfiniteTimeout, completionOption, method, path, queryString, headers, data, timeoutTokenSource.Token).ConfigureAwait(false));
                }
            }

            var request = PrepareRequest(method, path, queryString, headers, data);

            return(await _client.SendAsync(request, completionOption, cancellationToken).ConfigureAwait(false));
        }
Example #2
0
        private async Task <HttpResponseMessage> PrivateMakeRequestAsync(
            TimeSpan timeout,
            HttpCompletionOption completionOption,
            HttpMethod method,
            string path,
            IQueryString queryString,
            IDictionary <string, string> headers,
            IRequestContent data,
            CancellationToken cancellationToken)
        {
            var request = PrepareRequest(method, path, queryString, headers, data);

            if (timeout != s_InfiniteTimeout)
            {
                using (var timeoutTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
                {
                    timeoutTokenSource.CancelAfter(timeout);
                    return(await _client.SendAsync(request, completionOption, timeoutTokenSource.Token).ConfigureAwait(false));
                }
            }

            var tcs = new TaskCompletionSource <HttpResponseMessage>();

            using (cancellationToken.Register(() => tcs.SetCanceled()))
            {
                return(await await Task.WhenAny(tcs.Task, _client.SendAsync(request, completionOption, cancellationToken)).ConfigureAwait(false));
            }
        }
 internal async Task<DockerApiResponse> MakeRequestAsync(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IRequestContent data, TimeSpan? timeout, CancellationToken cancellationToken)
 {
     HttpResponseMessage response = await this.MakeRequestInnerAsync(null, HttpCompletionOption.ResponseContentRead, method, path, queryString, null, data, cancellationToken);
     string body = await response.Content.ReadAsStringAsync();
     HandleIfErrorResponse(response.StatusCode, body, errorHandlers);
     return new DockerApiResponse(response.StatusCode, body);
 }
Example #4
0
 public RestRequest(HttpMethod method, FormattableString url, IReadOnlyDictionary <string, object> queryStringParameters, IRequestContent content, RestRequestOptions options)
 {
     _tcs    = new TaskCompletionSource <HttpResponseMessage>();
     _url    = url;
     _method = method;
     _queryStringParameters = queryStringParameters;
     _content = content;
     Options  = options?.Clone();
 }
Example #5
0
 internal Task <Stream> MakeRequestForStreamAsync(
     IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers,
     HttpMethod method,
     string path,
     IQueryString queryString,
     IRequestContent body,
     CancellationToken token)
 {
     return(MakeRequestForStreamAsync(errorHandlers, method, path, queryString, body, null, token));
 }
Example #6
0
 internal Task <DockerApiResponse> MakeRequestAsync(
     IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers,
     HttpMethod method,
     string path,
     IQueryString queryString,
     IRequestContent body,
     IDictionary <string, string> headers,
     CancellationToken token)
 {
     return(MakeRequestAsync(errorHandlers, method, path, queryString, body, headers, this.DefaultTimeout, token));
 }
Example #7
0
 internal Task <WriteClosableStream> MakeRequestForHijackedStreamAsync(
     IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers,
     HttpMethod method,
     string path,
     IQueryString queryString,
     IRequestContent body,
     IDictionary <string, string> headers,
     CancellationToken cancellationToken)
 {
     return(MakeRequestForHijackedStreamAsync(errorHandlers, method, path, queryString, body, headers, s_InfiniteTimeout, cancellationToken));
 }
Example #8
0
        internal async Task <HttpResponseMessage> MakeRequestForRawResponseAsync(
            HttpMethod method,
            string path,
            IQueryString queryString,
            IRequestContent body,
            IDictionary <string, string> headers,
            CancellationToken token)
        {
            var response = await PrivateMakeRequestAsync(s_InfiniteTimeout, HttpCompletionOption.ResponseHeadersRead, method, path, queryString, headers, body, token).ConfigureAwait(false);

            return(response);
        }
Example #9
0
        internal override HttpContent Content(IRequestContent requestContent)
        {
            var xmlMessage     = Serialize(requestContent);
            var messageContent = new StringContent(xmlMessage);

            var boundary             = Guid.NewGuid().ToString();
            var mediaTypeHeaderValue = new MediaTypeHeaderValue(DigipostVersion.V7);

            mediaTypeHeaderValue.Parameters.Add(new NameValueWithParametersHeaderValue("boundary", boundary));
            messageContent.Headers.ContentType = mediaTypeHeaderValue;

            return(messageContent);
        }
        private void InitializeRequestXmlContent(IRequestContent requestContent)
        {
            if (requestContent == null)
            {
                return;
            }

            var document   = new XmlDocument();
            var serialized = Serialize(requestContent);

            document.LoadXml(serialized);
            RequestContent = document;
        }
Example #11
0
        protected virtual string GetSignOrigin(IRequestContent content)
        {
            var originBuilder = new StringBuilder();

            foreach (var paramater in content.Paramaters.OrderBy(x => x.Key))
            {
                if (paramater.Key.ToLower() == "sign")
                {
                    continue;
                }
                originBuilder.Append($"{paramater.Key}={paramater.Value}&");
            }
            return(originBuilder.ToString().TrimEnd('&'));
        }
Example #12
0
        public async Task <T> MakeRequestJsonAsync <T>(
            HttpMethod method,
            string path,
            String queryString   = null,
            IRequestContent body = null,
            Action <HttpRequestHeader> headersConfigure = null,
            TimeSpan?timeout        = null,
            CancellationToken?token = null,
            IEnumerable <RestResponseErrorHandlingDelegate> errorHandlers = null)
        {
            var response = await this.MakeRequestAsync(method, path, queryString, body, headersConfigure, timeout, token, errorHandlers);

            return(this.JsonSerializer.DeserializeObject <T>(response.Body));
        }
Example #13
0
        internal async Task <Stream> MakeRequestForStreamAsync(
            IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers,
            HttpMethod method,
            string path,
            IQueryString queryString,
            IRequestContent body,
            IDictionary <string, string> headers,
            TimeSpan timeout,
            CancellationToken token)
        {
            var response = await PrivateMakeRequestAsync(timeout, HttpCompletionOption.ResponseHeadersRead, method, path, queryString, headers, body, token).ConfigureAwait(false);

            await HandleIfErrorResponseAsync(response.StatusCode, response, errorHandlers);

            return(await response.Content.ReadAsStreamAsync().ConfigureAwait(false));
        }
Example #14
0
        public async Task <Stream> MakeRequestForStreamAsync(
            HttpMethod method,
            string path,
            String queryString   = null,
            IRequestContent body = null,
            Action <HttpRequestHeader> headersConfigure = null,
            TimeSpan?timeout        = null,
            CancellationToken?token = null,
            IEnumerable <RestResponseErrorHandlingDelegate> errorHandlers = null)
        {
            var response = await this.MakeRequestCoreAsync(method, path, queryString, body, timeout, token, HttpCompletionOption.ResponseHeadersRead, headersConfigure).ConfigureAwait(false);

            HandleIfErrorResponse(response.StatusCode, null, errorHandlers);

            return(await response.Content.ReadAsStreamAsync().ConfigureAwait(false));
        }
Example #15
0
        private async Task <HttpResponseMessage> MakeRequestCoreAsync(
            HttpMethod method,
            string path,
            String queryString   = null,
            IRequestContent data = null,
            TimeSpan?timeout     = null,
            CancellationToken?cancellationToken         = null,
            HttpCompletionOption completionOption       = HttpCompletionOption.ResponseContentRead,
            Action <HttpRequestHeader> headersConfigure = null)
        {
            var request = PrepareRequest(method, path, queryString, headersConfigure, data);

            CancellationToken token;

            if (timeout != InfiniteTimeout)
            {
                token = cancellationToken ?? CancellationToken.None;
                var timeoutTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);
                timeoutTokenSource.CancelAfter(timeout ?? this.Configuration.Timeout);
                token = timeoutTokenSource.Token;
            }

            try
            {
                var result = await _client.SendAsync(request, completionOption, token);

                return(result);
            }
            catch (OperationCanceledException cex)
            {
                String body = null;
                if (data != null)
                {
                    body = data.GetContent()?.ReadAsStringAsync()?.GetAwaiter().GetResult();
                }
                throw new SchubertRestTimeoutException($@"在 {(timeout ?? this.Configuration.Timeout).TotalSeconds.ToString()} 秒内没有收到服务端的 HTTP 响应(uri: {request.RequestUri?.ToString().IfNullOrWhiteSpace("null")}, data:{body.IfNullOrWhiteSpace("null")})调用的响应。", cex);
            }
            catch (Exception ex)
            {
                String body = null;
                if (data != null)
                {
                    body = data.GetContent()?.ReadAsStringAsync()?.GetAwaiter().GetResult();
                }
                throw new SchubertRestException(HttpStatusCode.BadRequest, $@"发送 HTTP 请求生错误(uri: {request.RequestUri?.ToString().IfNullOrWhiteSpace("null")}, data:{body.IfNullOrWhiteSpace("null")})发生错误。", ex);
            }
        }
        internal override HttpContent Content(IRequestContent requestContent)
        {
            var message  = requestContent as IMessage;
            var boundary = Guid.NewGuid().ToString();

            var multipartFormDataContent = new MultipartFormDataContent(boundary);

            var mediaTypeHeaderValue = new MediaTypeHeaderValue("multipart/vnd.digipost-v7+xml");

            mediaTypeHeaderValue.Parameters.Add(new NameValueWithParametersHeaderValue("boundary", boundary));
            multipartFormDataContent.Headers.ContentType = mediaTypeHeaderValue;

            AddBodyToContent(message, multipartFormDataContent);
            AddPrimaryDocumentToContent(message, multipartFormDataContent);
            AddAttachmentsToContent(message, multipartFormDataContent);

            return(multipartFormDataContent);
        }
Example #17
0
        public string Sign(IRequestContent content)
        {
            if (content.SignType != "RSA" && content.SignType != "RSA2")
            {
                throw new PaymentArgumentException(GateWay.Name, "sign_type", $"不支持的sign_type:{content.SignType}");
            }
            if (content.Encoding == null)
            {
                throw new PaymentArgumentException(GateWay.Name, "charset", "编码格式错误");
            }

            if (!(GateWay.MerchantConfigure is AlipayMerchantConfigure merchantConfigure))
            {
                throw new PaymentException(GateWay.Name, "商户信息错误");
            }

            return(SecurityUtiity.RSA(GetSignOrigin(content), merchantConfigure.PrivateKey, content.Encoding.BodyName, content.SignType, false));
        }
Example #18
0
        private Task <HttpResponseMessage> PrivateMakeRequestAsync(
            TimeSpan timeout,
            HttpCompletionOption completionOption,
            HttpMethod method,
            string path,
            IQueryString queryString,
            IDictionary <string, string> headers,
            IRequestContent data,
            CancellationToken cancellationToken)
        {
            var request = PrepareRequest(method, path, queryString, headers, data);

            if (timeout != s_InfiniteTimeout)
            {
                var timeoutTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                timeoutTokenSource.CancelAfter(timeout);
                cancellationToken = timeoutTokenSource.Token;
            }

            return(_client.SendAsync(request, completionOption, cancellationToken));
        }
Example #19
0
        internal async Task <WriteClosableStream> MakeRequestForHijackedStreamAsync(
            IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers,
            HttpMethod method,
            string path,
            IQueryString queryString,
            IRequestContent body,
            IDictionary <string, string> headers,
            TimeSpan timeout,
            CancellationToken cancellationToken)
        {
            var response = await PrivateMakeRequestAsync(timeout, HttpCompletionOption.ResponseHeadersRead, method, path, queryString, headers, body, cancellationToken).ConfigureAwait(false);

            await HandleIfErrorResponseAsync(response.StatusCode, response, errorHandlers);

            var content = response.Content as HttpConnectionResponseContent;

            if (content == null)
            {
                throw new NotSupportedException("message handler does not support hijacked streams");
            }

            return(content.HijackStream());
        }
Example #20
0
        public async Task <WriteClosableStream> MakeRequestForHijackedStreamAsync(
            HttpMethod method,
            string path,
            String queryString   = null,
            IRequestContent body = null,
            Action <HttpRequestHeader> headersConfigure = null,
            TimeSpan?timeout = null,
            CancellationToken?cancellationToken = null,
            IEnumerable <RestResponseErrorHandlingDelegate> errorHandlers = null)
        {
            var response = await MakeRequestCoreAsync(method, path, queryString, body, timeout, cancellationToken, HttpCompletionOption.ResponseHeadersRead, headersConfigure).ConfigureAwait(false);

            HandleIfErrorResponse(response.StatusCode, null, errorHandlers);

            var content = response.Content as HttpConnectionResponseContent;

            if (content == null)
            {
                throw new NotSupportedException("message handler does not support hijacked streams");
            }

            return(content.HijackStream());
        }
Example #21
0
        internal async Task <DockerApiStreamedResponse> MakeRequestForStreamedResponseAsync(IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IDictionary <string, string> headers, IRequestContent data, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await MakeRequestInnerAsync(TimeSpan.FromMilliseconds(Timeout.Infinite), HttpCompletionOption.ResponseHeadersRead, method, path, queryString, headers, data, cancellationToken);

            HandleIfErrorResponse(response.StatusCode, null, errorHandlers);

            Stream body = await response.Content.ReadAsStreamAsync();

            return(new DockerApiStreamedResponse(response.StatusCode, body, response.Headers));
        }
Example #22
0
        internal async Task <Stream> MakeRequestForStreamAsync(IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IDictionary <string, string> headers, IRequestContent data, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await MakeRequestInnerAsync(InfiniteTimeout, HttpCompletionOption.ResponseHeadersRead, method, path, queryString, headers, data, cancellationToken).ConfigureAwait(false);

            HandleIfErrorResponse(response.StatusCode, null, errorHandlers);

            return(await response.Content.ReadAsStreamAsync().ConfigureAwait(false));
        }
Example #23
0
        protected HttpRequestMessage PrepareRequest(HttpMethod method, string path, String queryString, Action <HttpRequestHeader> headerConfigure, IRequestContent data)
        {
            if (string.IsNullOrEmpty("path"))
            {
                throw new ArgumentNullException(nameof(path));
            }

            var request = new HttpRequestMessage(method, RestUtility.BuildUri(this.EndpointBaseUri, this._requestedApiVersion, path, queryString));

            request.Headers.TryAddWithoutValidation("User-Agent", UserAgent);
            foreach (var header in this.Configuration.DefaultHeaders)
            {
                request.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            headerConfigure?.Invoke(request.Headers);

            if (data != null)
            {
                var requestContent = data.GetContent(); // make the call only once.
                request.Content = requestContent;
            }

            return(request);
        }
Example #24
0
        private Task<HttpResponseMessage> MakeRequestInnerAsync(TimeSpan? requestTimeout, HttpCompletionOption completionOption, HttpMethod method, string path, IQueryString queryString, IDictionary<string, string> headers, IRequestContent data, CancellationToken cancellationToken)
        {
            HttpRequestMessage request = PrepareRequest(method, path, queryString, headers, data);

            if (requestTimeout.HasValue)
            {
                if (requestTimeout.Value != InfiniteTimeout)
                {
                    cancellationToken = CreateTimeoutToken(cancellationToken, requestTimeout.Value);
                }
            }
            else
            {
                cancellationToken = CreateTimeoutToken(cancellationToken, _defaultTimeout);
            }

            return _client.SendAsync(request, completionOption, cancellationToken);
        }
 protected DigipostAction(IRequestContent requestContent)
 {
     InitializeRequestXmlContent(requestContent);
 }
Example #26
0
 public RestRequest(HttpMethod method, FormattableString url, IRequestContent content, RestRequestOptions options) : this(method, url, null, content, options)
 {
 }
 internal Task<DockerApiResponse> MakeRequestAsync(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IRequestContent data)
 {
     return MakeRequestAsync(errorHandlers, method, path, queryString, data, null, CancellationToken.None);
 }
 internal Task<Stream> MakeRequestForStreamAsync(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IRequestContent data, CancellationToken cancellationToken)
 {
     return MakeRequestForStreamAsync(errorHandlers, method, path, queryString, null, data, cancellationToken);
 }
 internal async Task<Stream> MakeRequestForStreamAsync(IEnumerable<ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IDictionary<string, string> headers, IRequestContent data, CancellationToken cancellationToken)
 {
     HttpResponseMessage response = await MakeRequestInnerAsync(TimeSpan.FromMilliseconds(Timeout.Infinite), HttpCompletionOption.ResponseHeadersRead, method, path, queryString, headers, data, cancellationToken);
     HandleIfErrorResponse(response.StatusCode, null, errorHandlers);
     return await response.Content.ReadAsStreamAsync();
 }
        private async Task<HttpResponseMessage> MakeRequestInnerAsync(TimeSpan? requestTimeout, HttpCompletionOption completionOption, HttpMethod method, string path, IQueryString queryString, IDictionary<string, string> headers, IRequestContent data, CancellationToken cancellationToken)
        {
            HttpClient client = this.GetHttpClient();
            if (requestTimeout.HasValue)
            {
                client.Timeout = requestTimeout.Value;
            }

            HttpRequestMessage request = PrepareRequest(method, path, queryString, headers, data);
            return await client.SendAsync(request, completionOption, cancellationToken);
        }
Example #31
0
        internal async Task <DockerApiResponse> MakeRequestAsync(IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IDictionary <string, string> headers, IRequestContent data)
        {
            var response = await MakeRequestInnerAsync(null, HttpCompletionOption.ResponseContentRead, method, path, queryString, headers, data, default(CancellationToken)).ConfigureAwait(false);

            var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            HandleIfErrorResponse(response.StatusCode, body, errorHandlers);

            return(new DockerApiResponse(response.StatusCode, body));
        }
Example #32
0
        private Task <HttpResponseMessage> MakeRequestInnerAsync(TimeSpan?requestTimeout, HttpCompletionOption completionOption, HttpMethod method, string path, IQueryString queryString, IDictionary <string, string> headers, IRequestContent data, CancellationToken cancellationToken)
        {
            HttpRequestMessage request = PrepareRequest(method, path, queryString, headers, data);

            if (requestTimeout.HasValue)
            {
                if (requestTimeout.Value != InfiniteTimeout)
                {
                    cancellationToken = CreateTimeoutToken(cancellationToken, requestTimeout.Value);
                }
            }
            else
            {
                cancellationToken = CreateTimeoutToken(cancellationToken, _defaultTimeout);
            }

            return(_client.SendAsync(request, completionOption, cancellationToken));
        }
        internal HttpRequestMessage PrepareRequest(HttpMethod method, string path, IQueryString queryString, IDictionary<string, string> headers, IRequestContent data)
        {
            if (string.IsNullOrEmpty("path"))
            {
                throw new ArgumentNullException("path");
            }

            HttpRequestMessage request = new HttpRequestMessage(method, HttpUtility.BuildUri(this.Configuration.EndpointBaseUri, this.RequestedApiVersion, path, queryString));
            request.Headers.Add("User-Agent", UserAgent);
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            if (data != null)
            {
                HttpContent requestContent = data.GetContent(); // make the call only once.
                request.Content = requestContent;
            }

            return request;
        }
Example #34
0
        internal HttpRequestMessage PrepareRequest(HttpMethod method, string path, IQueryString queryString, IDictionary <string, string> headers, IRequestContent data)
        {
            if (string.IsNullOrEmpty("path"))
            {
                throw new ArgumentNullException("path");
            }

            HttpRequestMessage request = new HttpRequestMessage(method, HttpUtility.BuildUri(Configuration.EndpointBaseUri, RequestedApiVersion, path, queryString));

            request.Headers.Add("User-Agent", UserAgent);

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            if (data != null)
            {
                HttpContent requestContent = data.GetContent(); // make the call only once.
                request.Content = requestContent;
            }

            return(request);
        }
Example #35
0
 internal Task <DockerApiStreamedResponse> MakeRequestForStreamedResponseAsync(IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IRequestContent data, CancellationToken cancellationToken)
 {
     return(MakeRequestForStreamedResponseAsync(errorHandlers, method, path, queryString, null, data, cancellationToken));
 }
Example #36
0
        internal async Task <DockerApiResponse> MakeRequestAsync(IEnumerable <ApiResponseErrorHandlingDelegate> errorHandlers, HttpMethod method, string path, IQueryString queryString, IRequestContent data, TimeSpan?timeout, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await MakeRequestInnerAsync(null, HttpCompletionOption.ResponseContentRead, method, path, queryString, null, data, cancellationToken).ConfigureAwait(false);

            string body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            HandleIfErrorResponse(response.StatusCode, body, errorHandlers);

            return(new DockerApiResponse(response.StatusCode, body));
        }
Example #37
0
        private async Task <HttpResponseMessage> MakeRequestInnerAsync(TimeSpan?requestTimeout, HttpCompletionOption completionOption, HttpMethod method, string path, IQueryString queryString, IDictionary <string, string> headers, IRequestContent data, CancellationToken cancellationToken)
        {
            HttpClient client = this.GetHttpClient();

            if (requestTimeout.HasValue)
            {
                client.Timeout = requestTimeout.Value;
            }

            HttpRequestMessage request = PrepareRequest(method, path, queryString, headers, data);

            return(await client.SendAsync(request, completionOption, cancellationToken));
        }