예제 #1
0
        public async Task <string> MakeRequestAsync(string url, string baseUrl = null, Dictionary <string, object> payload = null, string method = null)
        {
            await default(SynchronizationContextRemover);
            await api.RateLimit.WaitToProceedAsync();

            if (url[0] != '/')
            {
                url = "/" + url;
            }
            string uri2 = (baseUrl ?? api.BaseUrl) + url;

            if (method == null)
            {
                method = api.RequestMethod;
            }
            Uri uri = api.ProcessRequestUrl(new UriBuilder(uri2), payload, method);
            InternalHttpWebRequest request = new InternalHttpWebRequest(uri)
            {
                Method = method
            };

            request.AddHeader("content-type", api.RequestContentType);
            request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36");
            int num3 = request.Timeout = (request.ReadWriteTimeout = (int)api.RequestTimeout.TotalMilliseconds);
            await api.ProcessRequestAsync(request, payload);

            try
            {
                RequestStateChanged?.Invoke(this, RequestMakerState.Begin, uri.AbsoluteUri);
                using var webHttpRequest  = request.ToHttpRequestMessage();
                using var webHttpResponse = await _httpClient.SendAsync(webHttpRequest, _cancellationToken);

                string text = await webHttpResponse.Content.ReadAsStringAsync();

                if (!webHttpResponse.IsSuccessStatusCode)
                {
                    if (string.IsNullOrWhiteSpace(text))
                    {
                        throw new APIException($"{webHttpResponse.StatusCode.ConvertInvariant<int>(0)} - {webHttpResponse.StatusCode}");
                    }
                    throw new APIException(text);
                }
                api.ProcessResponse(new InternalHttpWebResponse(webHttpResponse));
                // local reference to handle delegate becoming null, extended discussion here:
                // https://github.com/btcpayserver/btcpayserver/commit/00747906849f093712c3907c99404c55b3defa66#r37022103
                var requestStateChanged = RequestStateChanged;
                if (requestStateChanged != null)
                {
                    requestStateChanged(this, RequestMakerState.Finished, text);
                    return(text);
                }
                return(text);
            }
            catch (Exception arg)
            {
                RequestStateChanged?.Invoke(this, RequestMakerState.Error, arg);
                throw;
            }
        }
예제 #2
0
        /// <summary>
        /// ASYNC - Make a request to a path on the API
        /// </summary>
        /// <param name="url">Path and query</param>
        /// <param name="baseUrl">Override the base url, null for the default BaseUrl</param>
        /// <param name="payload">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>
        /// The encoding of payload is API dependant but is typically json.</param>
        /// <param name="method">Request method or null for default</param>
        /// <returns>Raw response</returns>
        public async Task <string> MakeRequestAsync(string url, string baseUrl = null, Dictionary <string, object> payload = null, string method = null)
        {
            await new SynchronizationContextRemover();

            await api.RateLimit.WaitToProceedAsync();

            if (string.IsNullOrWhiteSpace(url))
            {
                return(null);
            }
            else if (url[0] != '/')
            {
                url = "/" + url;
            }

            string         fullUrl = (baseUrl ?? api.BaseUrl) + url;
            Uri            uri     = api.ProcessRequestUrl(new UriBuilder(fullUrl), payload);
            HttpWebRequest request = HttpWebRequest.CreateHttp(uri);

            request.Headers["Accept-Language"] = "en-US,en;q=0.5";
            request.Method      = method ?? api.RequestMethod;
            request.ContentType = api.RequestContentType;
            request.UserAgent   = BaseAPI.RequestUserAgent;
            request.CachePolicy = api.RequestCachePolicy;
            request.Timeout     = request.ReadWriteTimeout = (int)api.RequestTimeout.TotalMilliseconds;
            try
            {
                // not supported on some platforms
                request.ContinueTimeout = (int)api.RequestTimeout.TotalMilliseconds;
            }
            catch
            {
            }
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            await api.ProcessRequestAsync(request, payload);

            HttpWebResponse response       = null;
            string          responseString = null;

            try
            {
                try
                {
                    RequestStateChanged?.Invoke(this, RequestMakerState.Begin, null);
                    response = await request.GetResponseAsync() as HttpWebResponse;

                    if (response == null)
                    {
                        throw new APIException("Unknown response from server");
                    }
                }
                catch (WebException we)
                {
                    response = we.Response as HttpWebResponse;
                    if (response == null)
                    {
                        throw new APIException(we.Message ?? "Unknown response from server");
                    }
                }
                using (Stream responseStream = response.GetResponseStream())
                {
                    responseString = new StreamReader(responseStream).ReadToEnd();
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        // 404 maybe return empty responseString
                        if (string.IsNullOrWhiteSpace(responseString))
                        {
                            throw new APIException(string.Format("{0} - {1}",
                                                                 response.StatusCode.ConvertInvariant <int>(), response.StatusCode));
                        }
                        throw new APIException(responseString);
                    }
                    api.ProcessResponse(response);
                    RequestStateChanged?.Invoke(this, RequestMakerState.Finished, responseString);
                }
            }
            catch (Exception ex)
            {
                RequestStateChanged?.Invoke(this, RequestMakerState.Error, ex);
                throw;
            }
            finally
            {
                response?.Dispose();
            }
            return(responseString);
        }
예제 #3
0
        /// <summary>
        /// ASYNC - Make a request to a path on the API
        /// </summary>
        /// <param name="url">Path and query</param>
        /// <param name="baseUrl">Override the base url, null for the default BaseUrl</param>
        /// <param name="payload">Payload, can be null. For private API end points, the payload must contain a 'nonce' key set to GenerateNonce value.</param>
        /// The encoding of payload is API dependant but is typically json.</param>
        /// <param name="method">Request method or null for default</param>
        /// <returns>Raw response</returns>
        public async Task <string> MakeRequestAsync(string url, string baseUrl = null, Dictionary <string, object> payload = null, string method = null)
        {
            await new SynchronizationContextRemover();

            await api.RateLimit.WaitToProceedAsync();

            if (string.IsNullOrWhiteSpace(url))
            {
                return(null);
            }
            else if (url[0] != '/')
            {
                url = "/" + url;
            }

            string         fullUrl = (baseUrl ?? api.BaseUrl) + url;
            Uri            uri     = api.ProcessRequestUrl(new UriBuilder(fullUrl), payload);
            HttpWebRequest request = HttpWebRequest.CreateHttp(uri);

            request.Headers["Accept-Language"] = "en-us; q=1.0;";
            request.Method      = method ?? api.RequestMethod;
            request.ContentType = api.RequestContentType;
            request.UserAgent   = BaseAPI.RequestUserAgent;
            request.CachePolicy = api.RequestCachePolicy;
            request.Timeout     = request.ReadWriteTimeout = (int)api.RequestTimeout.TotalMilliseconds;
            try
            {
                // not supported on some platforms
                request.ContinueTimeout = (int)api.RequestTimeout.TotalMilliseconds;
            }
            catch
            {
            }
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            api.ProcessRequest(request, payload);
            HttpWebResponse response;

            try
            {
                response = await request.GetResponseAsync() as HttpWebResponse;

                if (response == null)
                {
                    throw new APIException("Unknown response from server");
                }
            }
            catch (WebException we)
            {
                response = we.Response as HttpWebResponse;
                if (response == null)
                {
                    throw new APIException(we.Message ?? "Unknown response from server");
                }
            }
            string responseString = null;

            using (Stream responseStream = response.GetResponseStream())
            {
                responseString = new StreamReader(responseStream).ReadToEnd();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new APIException(responseString);
                }
                api.ProcessResponse(response);
            }
            response.Dispose();
            return(responseString);
        }
예제 #4
0
        public async Task <string> MakeRequestAsync(string url, string?baseUrl = null, Dictionary <string, object>?payload = null, string?method = null)
        {
            await new SynchronizationContextRemover();
            await api.RateLimit.WaitToProceedAsync();

            if (url[0] != '/')
            {
                url = "/" + url;
            }

            string fullUrl = (baseUrl ?? api.BaseUrl) + url;

            method ??= api.RequestMethod;
            Uri uri = api.ProcessRequestUrl(new UriBuilder(fullUrl), payload, method);
            InternalHttpWebRequest request = new InternalHttpWebRequest(uri)
            {
                Method = method
            };

            request.AddHeader("accept-language", "en-US,en;q=0.5");
            request.AddHeader("content-type", api.RequestContentType);
            request.AddHeader("user-agent", BaseAPI.RequestUserAgent);
            request.Timeout = request.ReadWriteTimeout = (int)api.RequestTimeout.TotalMilliseconds;
            await api.ProcessRequestAsync(request, payload);

            HttpWebResponse?response = null;
            string          responseString;

            try
            {
                try
                {
                    RequestStateChanged?.Invoke(this, RequestMakerState.Begin, uri.AbsoluteUri);// when start make a request we send the uri, this helps developers to track the http requests.
                    response = await request.Request.GetResponseAsync() as HttpWebResponse;

                    if (response == null)
                    {
                        throw new APIException("Unknown response from server");
                    }
                }
                catch (WebException we)
                {
                    response = we.Response as HttpWebResponse;
                    if (response == null)
                    {
                        throw new APIException(we.Message ?? "Unknown response from server");
                    }
                }
                using (Stream responseStream = response.GetResponseStream())
                    using (StreamReader responseStreamReader = new StreamReader(responseStream))
                        responseString = responseStreamReader.ReadToEnd();

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    // 404 maybe return empty responseString
                    if (string.IsNullOrWhiteSpace(responseString))
                    {
                        throw new APIException(string.Format("{0} - {1}", response.StatusCode.ConvertInvariant <int>(), response.StatusCode));
                    }

                    throw new APIException(responseString);
                }

                api.ProcessResponse(new InternalHttpWebResponse(response));
                RequestStateChanged?.Invoke(this, RequestMakerState.Finished, responseString);
            }
            catch (Exception ex)
            {
                RequestStateChanged?.Invoke(this, RequestMakerState.Error, ex);
                throw;
            }
            finally
            {
                response?.Dispose();
            }
            return(responseString);
        }