示例#1
0
        /// <summary>
        /// Executes the request and callback asynchronously, authenticating if needed
        /// </summary>
        /// <param name="request">Request to be executed</param>
        /// <param name="callback">Callback function to be executed upon completion providing access to the async handle.</param>
        public virtual RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action <IRestResponse, RestRequestAsyncHandle> callback)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            ConfigureHttp(request, http);

            HttpWebRequest webRequest  = null;
            var            asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> response_cb = r => ProcessResponse(r, asyncHandle, callback);

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = response_cb;

                response_cb = resp => ctx.Post(s => cb(resp), null);
            }

            switch (request.Method)
            {
            case Method.GET:
                webRequest = http.GetAsync(response_cb);
                break;

            case Method.POST:
                webRequest = http.PostAsync(response_cb);
                break;

            case Method.PUT:
                webRequest = http.PutAsync(response_cb);
                break;

            case Method.DELETE:
                webRequest = http.DeleteAsync(response_cb);
                break;

            case Method.HEAD:
                webRequest = http.HeadAsync(response_cb);
                break;

            case Method.OPTIONS:
                webRequest = http.OptionsAsync(response_cb);
                break;

            case Method.PATCH:
                webRequest = http.PatchAsync(response_cb);
                break;
            }

            asyncHandle.WebRequest = webRequest;
            return(asyncHandle);
        }
示例#2
0
        private async Task <IRestResponse> ExecuteInternal(IRestRequest request, string httpMethod, Func <IHttp, string, CacheMode, TimeSpan?, Task <HttpResponse> > getResponse)
        {
            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            this.AddDefaultParameter("Accept", "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml", ParameterType.HttpHeader);

            IRestResponse response = new RestResponse();

            try
            {
                var http = HttpFactory.Create();

                ConfigureHttp(request, http);

                response         = ConvertToRestResponse(request, await getResponse(http, httpMethod, request.CacheMode, request.CacheExpiry));
                response.Request = request;
                response.Request.IncreaseNumAttempts();
            }
            catch (Exception ex)
            {
                response.ResponseStatus = ResponseStatus.Error;
                response.ErrorMessage   = ex.Message;
                response.ErrorException = ex;
            }

            return(response);
        }
示例#3
0
        private IRestResponse Execute(IRestRequest request, string httpMethod,
                                      Func <IHttp, string, HttpResponse> getResponse)
        {
            AuthenticateIfNeeded(this, request);

            IRestResponse response = new RestResponse();

            try
            {
                var http = HttpFactory.Create();

                ConfigureHttp(request, http);

                response         = ConvertToRestResponse(request, getResponse(http, httpMethod));
                response.Request = request;
                response.Request.IncreaseNumAttempts();
            }
            catch (Exception ex)
            {
                response.ResponseStatus = ResponseStatus.Error;
                response.ErrorMessage   = ex.Message;
                response.ErrorException = ex;
            }

            return(response);
        }
示例#4
0
        /// <summary>
        /// Retrieves a list of records from Google's DNS over HTTP service at dns.google.com.
        /// The list is ordered by priority.
        /// </summary>
        public static async Task <List <string> > FromGoogle(string domain, string type, Proxy proxy = null,
                                                             int timeout = 30000, CancellationToken cancellationToken = default)
        {
            var url = $"{"https"}://dns.google.com/resolve?name={Uri.EscapeDataString(domain)}&type={type}";

            using var httpClient = HttpFactory.GetRLHttpClient(proxy, new()
            {
                ConnectTimeout   = TimeSpan.FromMilliseconds(timeout),
                ReadWriteTimeout = TimeSpan.FromMilliseconds(timeout)
            });

            using var request = new HttpRequest
                  {
                      Uri = new Uri(url),
                  };

            using var response = await httpClient.SendAsync(request, cancellationToken);

            var json = await response.Content.ReadAsStringAsync(cancellationToken);

            var obj = JObject.Parse(json);

            return(obj["Answer"]
                   .Select(i => i.Value <string>("data"))
                   .Select(i => (int.Parse(i.Split(' ')[0]), i.Split(' ')[1]))
                   .OrderBy(kvp => kvp.Item1)
                   .Select(kvp => kvp.Item2.TrimEnd('.'))
                   .ToList());
        }
示例#5
0
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod, Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            ConfigureHttp(request, http);

            var asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> response_cb = r => ProcessResponse(request, r, asyncHandle, callback);

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = response_cb;

                response_cb = resp => ctx.Post(s => cb(resp), null);
            }

            asyncHandle.WebRequest = getWebRequest(http, response_cb, httpMethod);
            return(asyncHandle);
        }
示例#6
0
    /// <summary>
    /// HTTP消息监听器
    /// </summary>
    /// <param name="address">监听器监听的地址</param>
    /// <param name="port">监听器监听的端口</param>
    /// <param name="httpFactory">用于该HTTP协议栈的依赖注入器</param>
    internal HttpListener(IPAddress address, int port, HttpFactory httpFactory)
    {
      Address = address;
      Port = port;

      _factory = httpFactory;
    }
        private IRestResponse Execute(IRestRequest request, string httpMethod, Func <IHttp, string, HttpResponse> getResponse)
        {
            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            IRestResponse response = new RestResponse();

            try
            {
                var http = HttpFactory.Create();

                ConfigureHttp(request, http);
                ConfigureProxy(http);

                response         = ConvertToRestResponse(request, getResponse(http, httpMethod));
                response.Request = request;
                response.Request.IncreaseNumAttempts();
            }
            catch (Exception ex)
            {
                response.ResponseStatus = ResponseStatus.Error;
                response.ErrorMessage   = ex.Message;
                response.ErrorException = ex;
            }

            return(response);
        }
示例#8
0
文件: Server.cs 项目: Kayomani/FAP
	    /// <summary>
		/// Initializes a new instance of the <see cref="Server"/> class.
		/// </summary>
		/// <param name="factory">Factory used to create objects used in this library.</param>
		public Server(HttpFactory factory)
		{
	        ServerName = "C# WebServer";
			_server = this;
			_factory = factory;
            AuthenticationProvider = new AuthenticationProvider();
		}
        public virtual Request SendAsync(HttpMethod method, string resource)
        {
            Uri uri = new Uri(BaseClient.BaseAddress, resource);
            HttpRequestMessage message = HttpFactory.GetRequestMessage(method, uri, Formatters);

            return(SendAsync(message));
        }
示例#10
0
        /// <summary>
        /// Executes the request and callback asynchronously, authenticating if needed
        /// </summary>
        /// <param name="request">Request to be executed</param>
        /// <param name="callback">Callback function to be executed upon completion</param>
        public virtual void ExecuteAsync(RestRequest request, Action <RestResponse> callback)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            ConfigureHttp(request, http);

            switch (request.Method)
            {
            case Method.GET:
                http.GetAsync(r => ProcessResponse(r, callback));
                break;

            case Method.POST:
                http.PostAsync(r => ProcessResponse(r, callback));
                break;

            case Method.PUT:
                http.PutAsync(r => ProcessResponse(r, callback));
                break;

            case Method.DELETE:
                http.DeleteAsync(r => ProcessResponse(r, callback));
                break;

            case Method.HEAD:
                http.HeadAsync(r => ProcessResponse(r, callback));
                break;

            case Method.OPTIONS:
                http.OptionsAsync(r => ProcessResponse(r, callback));
                break;
            }
        }
示例#11
0
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request,
                                                    Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod,
                                                    Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            ConfigureHttp(request, http);

            var asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> response_cb = r => ProcessResponse(request, r, asyncHandle, callback);

#if !PocketPC
            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = response_cb;

                response_cb = resp => ctx.Post(s => cb(resp), null);
            }
#endif

            asyncHandle.WebRequest = getWebRequest(http, response_cb, httpMethod);
            return(asyncHandle);
        }
示例#12
0
        /*
         * These are not blocks, but they take BotData as an input. The HttpRequestBlockInstance will take care
         * of writing C# code that calls these methods where necessary once it's transpiled.
         */

        // STANDARD REQUESTS
        // This method is accessed via a custom descriptor so it must not be an auto block
        public static async Task HttpRequestStandard(BotData data, StandardHttpRequestOptions options)
        {
            var clientOptions = GetClientOptions(data, options);

            using var client = HttpFactory.GetRLHttpClient(data.UseProxy ? data.Proxy : null, clientOptions);

            foreach (var cookie in options.CustomCookies)
            {
                data.COOKIES[cookie.Key] = cookie.Value;
            }

            using var request = new HttpRequest
                  {
                      Method  = new System.Net.Http.HttpMethod(options.Method.ToString()),
                      Uri     = new Uri(options.Url),
                      Version = Version.Parse(options.HttpVersion),
                      Headers = options.CustomHeaders,
                      Cookies = data.COOKIES,
                      AbsoluteUriInFirstLine = options.AbsoluteUriInFirstLine
                  };

            if (!string.IsNullOrEmpty(options.Content) || options.AlwaysSendContent)
            {
                var content = options.Content;

                if (options.UrlEncodeContent)
                {
                    content = string.Join("", content.SplitInChunks(2080)
                                          .Select(s => Uri.EscapeDataString(s)))
                              .Replace($"%26", "&").Replace($"%3D", "=");
                }

                request.Content = new StringContent(content.Unescape());
                request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(options.ContentType);
            }

            data.Logger.LogHeader();

            try
            {
                Activity.Current     = null;
                using var timeoutCts = new CancellationTokenSource(options.TimeoutMilliseconds);
                using var linkedCts  = CancellationTokenSource.CreateLinkedTokenSource(data.CancellationToken, timeoutCts.Token);
                using var response   = await client.SendAsync(request, linkedCts.Token);

                LogHttpRequestData(data, client);
                await LogHttpResponseData(data, response, request, options);
            }
            catch
            {
                LogHttpRequestData(data, request);
                throw;
            }
            finally
            {
                request.Dispose();
                client.Dispose();
            }
        }
示例#13
0
        public BaseTest()
        {
            var factory    = new HttpFactory();
            var logger     = new MockLogger();
            var mockLogger = new Mock <ILogger>();

            mock_client = new Mock <IApiClient>();
        }
        public async Task GetRows(IGetRowsParams getParams)
        {
            try
            {
                var url = "https://jsonplaceholder.typicode.com/photos?";

                if (AlbumIds?.Length > 0)
                {
                    foreach (var aid in AlbumIds)
                    {
                        url += $"&albumId={aid}";
                    }
                }
                else
                {
                    url += "&albumId=-1";
                }

                // https://github.com/typicode/json-server#slice
                url += $"&_start={getParams.StartRow}";
                url += $"&_end={getParams.EndRow}";

                if (getParams.SortModel?.Length > 0)
                {
                    // https://github.com/typicode/json-server#sort
                    url += $"&_sort={string.Join(",", getParams.SortModel.Select(sm => sm.ColumnId))}";
                    url += $"&_order={string.Join(",", getParams.SortModel.Select(sm => sm.Direction))}";
                }

                // TODO: FILTER

                using var http = HttpFactory.CreateClient();

                Console.WriteLine("Fetching from [{0}]", url);
                var resp = await http.GetAsync(url);

                resp.EnsureSuccessStatusCode();

                // https://github.com/typicode/json-server#slice
                resp.Headers.TryGetValues("X-Total-Count", out var totalCountHeader);
                var totalCount = int.TryParse(totalCountHeader?.FirstOrDefault(), out var totalCountInt)
                    ? (int?)totalCountInt
                    : null;

                var photos = await http.GetJsonAsync <Photo[]>(url);

                //Console.WriteLine("From [{0}:{1}], got [{2}] row(s) out of [{3}]",
                //    getParams.StartRow, getParams.EndRow, photos.Length, totalCount);

                await getParams.SuccessCallback(photos, totalCount);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to retrieve!");
                Console.WriteLine(ex.ToString());
                await getParams.FailCallback();
            }
        }
示例#15
0
        public static async Task <string> CreateAsync(
            int companyId,
            string lastName,
            string firstName,
            string lastNameKana,
            string firstNameKana,
            DateTime birthDate,
            DateTime entryDate,
            string payCalcType,
            int payAmount,
            string?num = null,
            string?workingHoursSystemName       = null,
            string?companyReferenceDateRuleName = null,
            int?gender    = null,
            bool?marriedF = null)
        {
            var o = new {
                company_id = companyId,
                employee   = new {
                    num = num,
                    working_hours_system_name        = workingHoursSystemName,
                    company_reference_date_rule_name = companyReferenceDateRuleName,
                    last_name       = lastName,
                    first_name      = firstName,
                    last_name_kana  = lastNameKana,
                    first_name_kana = firstNameKana,
                    birth_date      = birthDate.ToString("yyyy-MM-dd"),
                    entry_date      = entryDate.ToString("yyyy-MM-dd"),
                    pay_calc_type   = payCalcType,
                    pay_amount      = payAmount,
                    gender          = gender,
                    married_f       = marriedF
                }
            };


            var api  = FreeeAPIFactory.GetInstance();
            var json = JsonConvert.SerializeObject(
                o,
                new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            using (var content = new StringContent(
                       content:   json,
                       encoding:  Encoding.UTF8,
                       mediaType: "application/json"))
                using (var req = api.PostRequest(
                           url:       "https://api.freee.co.jp/hr/api/v1/employees",
                           content:   content,
                           useBearer: true)) {
                    var resp = await HttpFactory.GetInstance().SendAsync(req);

                    return(await api.GetContentAsync(resp));
                }
        }
示例#16
0
文件: Server.cs 项目: sclcwwl/Gimela
    /// <summary>
    /// 初始化HTTP服务器的实例
    /// </summary>
    /// <param name="serverName">Name of the server.</param>
    /// <param name="factory">Factory used to create objects used in this library.</param>
    public Server(string serverName, HttpFactory factory)
    {
      _server = this;
      _factory = factory;

      ServerName = serverName;

      AuthenticationProvider = new AuthenticationProvider();
      MaxContentSize = 1000000;
    }
示例#17
0
 public MockedEncompassHttpClientService(ILogger <MockedEncompassHttpClientService> logger)
 {
     _logger                  = logger;
     MockedHandler            = new Mock <HttpMessageHandler>();
     HttpFactory              = MockedHandler.CreateClientFactory();
     MockedClient             = HttpFactory.CreateClient("EncompassClient");
     BaseAddress              = new Uri(Faker.Internet.Url());
     MockedClient.BaseAddress = BaseAddress;
     MockedEncompassClient    = new EncompassApiService(MockedClient, new ClientParameters());
 }
示例#18
0
        /// <summary></summary>
        public static async Task <string> GetCompanyEmployeesAsync(
            int companyId,
            int per  = 0,
            int page = 25)
        {
            var api = FreeeAPIFactory.GetInstance();

            using (var req = api.GetRequest($"https://api.freee.co.jp/hr/api/v1/companies/{companyId}/employees"))
                using (var resp = await HttpFactory.GetInstance().SendAsync(req)) {
                    return(await api.GetContentAsync(resp));
                }
        }
示例#19
0
        public void CreateNotSupportActionTest()
        {
            var factory = new HttpFactory();

            Assert.Throws(typeof(ArgumentOutOfRangeException), () =>
            {
                factory.CreateHttp(HttpRequestActionType.None)
                .Setup()
                .SetUrl("http://localhost")
                .SetContent("");
            });
        }
示例#20
0
        /// <summary>
        /// 执行方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public T Execute <T>(IWeiXinRequest <T> request) where T : WeiXinResponse
        {
            //获得httpMethodAttribute数据.
            Type info = request.GetType();
            var  HttpAttributeInfo = (HttpMethodAttribute)System.Attribute.GetCustomAttribute(info, typeof(HttpMethodAttribute));
            ///根据不同的请求方式
            Http <T> http = HttpFactory <T> .CreateHttp(HttpAttributeInfo.Method);

            //延签消息
            http.Token = Token;
            http.HttpMethodAttribute = HttpAttributeInfo;
            http.Request             = request;
            return(http.GetResponse());
        }
        /// <summary>
        /// Initiate the payment by calling Flutterwave internal API with the collected payment details
        /// </summary>
        /// <param name="tx_ref">Your transaction reference. This MUST be unique for every transaction</param>
        /// <param name="amount">Amount to charge the customer.</param>
        /// <param name="redirect_url">URL to redirect to when a transaction is completed</param>
        /// <param name="customerEmail">Customer's email address</param>
        /// <param name="customerPhone">Customer's phone number</param>
        /// <param name="customerName">Customer's name</param>
        /// <param name="siteTile">Title to diplay on the flutterwave payment modal</param>
        /// <param name="siteDescription">Description to diplay on the flutterwave payment modal</param>
        /// <param name="siteLogoUrl">Logo to diplay on the flutterwave payment modal</param>
        /// <param name="payment_options">This specifies the payment options to be displayed e.g - card, mobilemoney, ussd and so on.</param>
        /// <param name="currency">Currency to charge in. Defaults to NGN</param>
        /// <returns>Payment link</returns>
        public async Task <TransactionInitResponseDTO> InitializeTransaction(string tx_ref, string amount,
                                                                             string redirect_url, string customerEmail, string customerPhone,
                                                                             string customerName, string payment_options = "card", string currency = "NGN")
        {
            //Build the input model from the paramters

            var model = new TransactionInitInputDTO()
            {
                amount   = amount,
                currency = currency,
                tx_ref   = tx_ref,
                customer = new Customer()
                {
                    email       = customerEmail,
                    name        = customerName,
                    phonenumber = customerPhone
                },
                redirect_url    = redirect_url,
                payment_options = payment_options,
                customizations  = new Customizations()
                {
                    title       = RaveConstant.SITE_TITLE,
                    description = RaveConstant.SITE_DESCRIPTION,
                    logo        = RaveConstant.COY_LOGO_URL
                }
            };

            //create httpclient here

            var _client = HttpFactory.InitHttpClient(RaveConstant.BASE_URL)
                          .AddAuthorizationHeader(RaveConstant.AUTHORIZATION_TYPE, _secretKey)
                          .AddMediaType(RaveConstant.REQUEST_MEDIA_TYPE)
                          .AddHeader("cache-control", "no-cache");

            //Build the request body as json
            var jsonObj = JsonSerializer.Serialize(model);

            var content = new StringContent(jsonObj, Encoding.UTF8, RaveConstant.REQUEST_MEDIA_TYPE);

            content.Headers.ContentType = new MediaTypeHeaderValue(RaveConstant.REQUEST_MEDIA_TYPE);


            //send the request
            var response = await _client.PostAsync("payments", content);

            var json = await response.Content.ReadAsStringAsync();

            //Deserialize and send the response
            return(JsonSerializer.Deserialize <TransactionInitResponseDTO>(json));
        }
        /// <summary>
        /// Use to verify payment transaction
        /// </summary>
        /// <param name="transaction_id">The Id of the transaction to verify</param>
        /// <returns></returns>
        public async Task <TransactionVerifyResponseDTO> VerifyTransaction(int transaction_id)
        {
            var _client = HttpFactory.InitHttpClient(RaveConstant.BASE_URL)
                          .AddAuthorizationHeader(RaveConstant.AUTHORIZATION_TYPE, _secretKey)
                          .AddMediaType(RaveConstant.REQUEST_MEDIA_TYPE)
                          .AddHeader("cache-control", "no-cache");

            //Send the request
            var response = await _client.GetAsync($"transactions/{transaction_id}/verify");

            var json = await response.Content.ReadAsStringAsync();

            return(JsonSerializer.Deserialize <TransactionVerifyResponseDTO>(json));
        }
示例#23
0
        public async System.Threading.Tasks.Task CreateHttpActionTestAsync()
        {
            var options = new HttpOptions();

            options.AddFileExtAsContentType(".txt", "is txt file");

            var factory = new HttpFactory(options);
            var httpGet = factory.CreateHttp(HttpRequestActionType.Get)
                          .Setup()
                          .SetUrl("http://www.baidu.com");

            var response = await httpGet.GetResponseAsync();

            Assert.NotEmpty(response);
        }
示例#24
0
        // BASIC AUTH
        // This method is accessed via a custom descriptor so it must not be an auto block
        public static async Task HttpRequestBasicAuth(BotData data, BasicAuthHttpRequestOptions options)
        {
            var clientOptions = GetClientOptions(data, options);

            using var client = HttpFactory.GetRLHttpClient(data.UseProxy ? data.Proxy : null, clientOptions);

            foreach (var cookie in options.CustomCookies)
            {
                data.COOKIES[cookie.Key] = cookie.Value;
            }

            using var request = new HttpRequest
                  {
                      Method  = new System.Net.Http.HttpMethod(options.Method.ToString()),
                      Uri     = new Uri(options.Url),
                      Version = Version.Parse(options.HttpVersion),
                      Headers = options.CustomHeaders,
                      Cookies = data.COOKIES,
                      AbsoluteUriInFirstLine = options.AbsoluteUriInFirstLine
                  };

            // Add the basic auth header
            request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(
                                  Encoding.UTF8.GetBytes($"{options.Username}:{options.Password}")));

            data.Logger.LogHeader();

            try
            {
                Activity.Current     = null;
                using var timeoutCts = new CancellationTokenSource(options.TimeoutMilliseconds);
                using var linkedCts  = CancellationTokenSource.CreateLinkedTokenSource(data.CancellationToken, timeoutCts.Token);
                using var response   = await client.SendAsync(request, linkedCts.Token);

                LogHttpRequestData(data, client);
                await LogHttpResponseData(data, response, request, options);
            }
            catch
            {
                LogHttpRequestData(data, request);
                throw;
            }
            finally
            {
                request.Dispose();
                client.Dispose();
            }
        }
示例#25
0
        // RAW REQUESTS
        // This method is accessed via a custom descriptor so it must not be an auto block
        public static async Task HttpRequestRaw(BotData data, RawHttpRequestOptions options)
        {
            var clientOptions = GetClientOptions(data, options);

            using var client = HttpFactory.GetRLHttpClient(data.UseProxy ? data.Proxy : null, clientOptions);

            foreach (var cookie in options.CustomCookies)
            {
                data.COOKIES[cookie.Key] = cookie.Value;
            }

            using var request = new HttpRequest
                  {
                      Method  = new System.Net.Http.HttpMethod(options.Method.ToString()),
                      Uri     = new Uri(options.Url),
                      Version = Version.Parse(options.HttpVersion),
                      Headers = options.CustomHeaders,
                      Cookies = data.COOKIES,
                      AbsoluteUriInFirstLine = options.AbsoluteUriInFirstLine,
                      Content = new ByteArrayContent(options.Content)
                  };

            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(options.ContentType);

            data.Logger.LogHeader();

            try
            {
                Activity.Current     = null;
                using var timeoutCts = new CancellationTokenSource(options.TimeoutMilliseconds);
                using var linkedCts  = CancellationTokenSource.CreateLinkedTokenSource(data.CancellationToken, timeoutCts.Token);
                using var response   = await client.SendAsync(request, linkedCts.Token);

                LogHttpRequestData(data, client);
                await LogHttpResponseData(data, response, request, options);
            }
            catch
            {
                LogHttpRequestData(data, request);
                throw;
            }
            finally
            {
                request.Dispose();
                client.Dispose();
            }
        }
示例#26
0
        public void GetResponseTest()
        {
            var request    = new AccessTokenRequest(new AppIdentication("james", "mySecret"));
            var factory    = new HttpFactory();
            var logger     = new MockLogger();
            var mockLogger = new Mock <ILogger>();
            var client     = new Mock <DefaultApiClient>(logger, factory);

            client.Setup(api => api.DoExecute(request))
            .Returns(new Task <string>(() => "{\"access_token\":\"ACCESS_TOKEN\",\"expires_in\":7200}"));

            var response = client.Object.Execute(request);

            Assert.Equal(0, response.ErrorCode);
            Assert.Equal("ACCESS_TOKEN", response.Access_Token);
            Assert.Equal(7200, response.Expires_In);
        }
示例#27
0
        public RetornoAssinaturaDTO Assinar(AssinaturaDTO assinatura)
        {
            var url = URLsBase.ASSINATURA;
            var httpFactory = new HttpFactory(_ambiente);

            using (var client = httpFactory.GetHttpClient())
            {
                var response = httpFactory.PostAsync(client, url, assinatura).Result;

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(response.Content.ReadAsStringAsync().Result);
                }

                return response.Content.ReadAsAsync<RetornoAssinaturaDTO>().Result;
            }
        }
示例#28
0
        private IRestResponse GetResponse(IRestRequest request)
        {
            var http = HttpFactory.Create();

            ConfigureHttp(request, http);
            ConfigureProxy(http);

            var httpResponse = new HttpResponse();

            switch (request.Method)
            {
            case Method.GET:
                httpResponse = http.Get();
                break;

            case Method.POST:
                httpResponse = http.Post();
                break;

            case Method.PUT:
                httpResponse = http.Put();
                break;

            case Method.DELETE:
                httpResponse = http.Delete();
                break;

            case Method.HEAD:
                httpResponse = http.Head();
                break;

            case Method.OPTIONS:
                httpResponse = http.Options();
                break;

            case Method.PATCH:
                httpResponse = http.Patch();
                break;
            }

            var restResponse = ConvertToRestResponse(request, httpResponse);

            return(restResponse);
        }
        public override async Task MediateAsync(Guid hash, BasicDeliverEventArgs data)
        {
            try
            {
                string json = this.GetMessage(data);
                this.logger?.Verbose("{name} [{hash}] message json: {json}", this.GetName(), hash, json);
                QueueHttpMessage message = this.DeserializeMessage(json);
                this.logger?.Verbose("{name} [{hash}] message object: {message}", this.GetName(), hash, JsonConvert.SerializeObject(message));
                HttpRequest request = HttpFactory.MakeRequest(message);
                this.logger?.Verbose("{name} [{hash}] request: {request}", this.GetName(), hash, JsonConvert.SerializeObject(request));
                await this.sender.SendAsync(request);

                this.logger?.Debug("{name} [{hash}] request status: {status}!", this.GetName(), hash, "success");
            }
            catch (Exception ex)
            {
                this.logger?.Warning(ex, "{name} [{hash}] request status: {status}. Message: {message}", this.GetName(), hash, "fail", ex.Message);
            }
        }
        /// <summary>
        /// Executes the request and callback asynchronously, authenticating if needed
        /// </summary>
        /// <param name="request">Request to be executed</param>
        /// <param name="callback">Callback function to be executed upon completion</param>
        public virtual void ExecuteAsync(RestRequest request, Action <RestResponse> callback)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            ConfigureHttp(request, http);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            switch (request.Method)
            {
            case Method.GET:
                http.GetAsync(r => ProcessResponse(r, callback));
                break;

            case Method.POST:
                http.PostAsync(r => ProcessResponse(r, callback));
                break;

            case Method.PUT:
                http.PutAsync(r => ProcessResponse(r, callback));
                break;

            case Method.DELETE:
                http.DeleteAsync(r => ProcessResponse(r, callback));
                break;

            case Method.HEAD:
                http.HeadAsync(r => ProcessResponse(r, callback));
                break;

            case Method.OPTIONS:
                http.OptionsAsync(r => ProcessResponse(r, callback));
                break;
            }
        }
示例#31
0
        public KvkApiClient(KvkApiClientConfig config)
        {
            _config = config ?? throw new ArgumentNullException(nameof(config));
            if (string.IsNullOrEmpty(config.ApiKey))
            {
                throw new ArgumentNullException(nameof(config.ApiKey));
            }
            if (string.IsNullOrEmpty(config.Endpoint))
            {
                throw new ArgumentNullException(nameof(config.Endpoint));
            }

            // initialize a HttpClient with custom handler, that uses the KvK-specific (root) certificates
            var httpClient = new HttpClient(KvkCertificateBuilder.CreateHttpHandler());

            // initialize the headers
            _headers = new Dictionary <string, string> {
                { "apikey", config.ApiKey }
            };

            _http = new HttpFactory(httpClient);
        }
示例#32
0
        // MULTIPART
        // This method is accessed via a custom descriptor so it must not be an auto block
        public static async Task HttpRequestMultipart(BotData data, MultipartHttpRequestOptions options)
        {
            var clientOptions = GetClientOptions(data, options);

            using var client = HttpFactory.GetRLHttpClient(data.UseProxy ? data.Proxy : null, clientOptions);

            foreach (var cookie in options.CustomCookies)
            {
                data.COOKIES[cookie.Key] = cookie.Value;
            }

            if (string.IsNullOrWhiteSpace(options.Boundary))
            {
                options.Boundary = GenerateMultipartBoundary();
            }

            // Rewrite the value of the Content-Type header otherwise it will add double quotes around it like
            // Content-Type: multipart/form-data; boundary="------WebKitFormBoundaryewozmkbxwbblilpm"
            var multipartContent = new MultipartFormDataContent(options.Boundary);

            multipartContent.Headers.ContentType.Parameters.First(o => o.Name == "boundary").Value = options.Boundary;

            FileStream fileStream = null;

            foreach (var c in options.Contents)
            {
                switch (c)
                {
                case StringHttpContent x:
                    multipartContent.Add(new StringContent(x.Data, Encoding.UTF8, x.ContentType), x.Name);
                    break;

                case RawHttpContent x:
                    var byteContent = new ByteArrayContent(x.Data);
                    byteContent.Headers.ContentType = new MediaTypeHeaderValue(x.ContentType);
                    multipartContent.Add(byteContent, x.Name);
                    break;

                case FileHttpContent x:
                    lock (FileLocker.GetHandle(x.FileName))
                    {
                        if (data.Providers.Security.RestrictBlocksToCWD)
                        {
                            FileUtils.ThrowIfNotInCWD(x.FileName);
                        }

                        fileStream = new FileStream(x.FileName, FileMode.Open);
                        var fileContent = CreateFileContent(fileStream, x.Name, Path.GetFileName(x.FileName), x.ContentType);
                        multipartContent.Add(fileContent, x.Name);
                    }
                    break;
                }
            }

            using var request = new HttpRequest
                  {
                      Method  = new System.Net.Http.HttpMethod(options.Method.ToString()),
                      Uri     = new Uri(options.Url),
                      Version = Version.Parse(options.HttpVersion),
                      Headers = options.CustomHeaders,
                      Cookies = data.COOKIES,
                      AbsoluteUriInFirstLine = options.AbsoluteUriInFirstLine,
                      Content = multipartContent
                  };

            data.Logger.LogHeader();

            try
            {
                Activity.Current     = null;
                using var timeoutCts = new CancellationTokenSource(options.TimeoutMilliseconds);
                using var linkedCts  = CancellationTokenSource.CreateLinkedTokenSource(data.CancellationToken, timeoutCts.Token);
                using var response   = await client.SendAsync(request, linkedCts.Token);

                LogHttpRequestData(data, client);
                await LogHttpResponseData(data, response, request, options);
            }
            catch
            {
                LogHttpRequestData(data, request, options.Boundary, options.Contents);
                throw;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                }

                request.Dispose();
                client.Dispose();
            }
        }
示例#33
0
		/// <summary>
		/// Initializes a new instance of the <see cref="HttpListener"/> class.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="port">The port.</param>
		protected HttpListener(IPAddress address, int port)
		{
			Address = address;
			Port = port;
			_factory = new HttpFactory();
		}
示例#34
0
		/// <summary>
		/// Creates a new <see cref="HttpListener"/> instance with default factories.
		/// </summary>
		/// <param name="address">Address that the listener should accept connections on.</param>
		/// <param name="port">Port that listener should accept connections on.</param>
		/// <param name="factory">Factory used to create different types in the framework.</param>
		/// <returns>Created HTTP listener.</returns>
		public static HttpListener Create(IPAddress address, int port, HttpFactory factory)
		{
			return new HttpListener(address, port);
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="Server"/> class.
		/// </summary>
		/// <param name="factory">Factory used to create objects used in this library.</param>
		public Server(HttpFactory factory)
		{
			_server = this;
			_factory = factory;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="Server"/> class.
		/// </summary>
		public Server()
		{
			_server = this;
			_factory = new HttpFactory();
		}