コード例 #1
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);
        }
コード例 #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
ファイル: CommandArgument.cs プロジェクト: cuiopen/ZeroNet
 /// <summary>
 ///     发出状态修改事件
 /// </summary>
 public void OnRequestStateChanged(CommandArgument argument)
 {
     RequestStateChanged?.Invoke(this, argument);
 }