Exemple #1
0
        public static RestClient CreateMockRestClient(string baseUrl, MockHttpMessageHandler messageHandler)
        {
            var restClientOptions = new RestClientOptions(baseUrl);
            var restClient        = new RestClient(messageHandler.ToHttpClient(), restClientOptions);

            return(restClient);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        public KeycloakOpenId()
        {
            if (string.IsNullOrEmpty(KeycloakConfiguration.BaseUrl))
            {
                throw new KeycloakOpenIdException($"Not specify URL address for authentication user by \"{KeycloakConfiguration.Protocol}\"");
            }

            if (KeycloakConfiguration.Protocol == "openid-connect")
            {
                var options = new RestClientOptions(KeycloakConfiguration.BaseUrl)
                {
                    Encoding    = Encoding.UTF8,
                    CachePolicy = new CacheControlHeaderValue()
                    {
                        NoCache = true,
                        NoStore = true
                    },
                    Timeout = KeycloakConfiguration.ConnectionTimeout
                };
                _basicRestClient = new RestClient(options);
            }
            else
            {
                throw new NotImplementedException("Other client protocol than 'open-id' connect is not implemented. Please switch the client to 'openid-connect'.");
            }
        }
    async Task AssertBody(Method method, bool disableCharset = false)
    {
        var options = new RestClientOptions(_server.Url)
        {
            DisableCharset = disableCharset
        };
        var client = new RestClient(options);

        var request = new RestRequest(RequestBodyCapturer.Resource, method)
        {
            OnBeforeRequest = async m => {
                _output.WriteLine(m.ToString());
                _output.WriteLine(await m.Content !.ReadAsStringAsync());
            }
        };

        const string bodyData = "abc123 foo bar baz BING!";

        request.AddParameter(TextPlainContentType, bodyData, ParameterType.RequestBody);

        await client.ExecuteAsync(request);

        var expected = disableCharset ? ExpectedTextContentTypeNoCharset : ExpectedTextContentType;

        AssertHasRequestBody(expected, bodyData);
    }
    public TwitterClient(string apiKey, string apiKeySecret)
    {
        var options = new RestClientOptions("https://api.twitter.com/2");

        _client = new RestClient(options)
        {
            Authenticator = new TwitterAuthenticator("https://api.twitter.com", apiKey, apiKeySecret)
        };
    }
Exemple #5
0
    public async Task GetRequestWithContentType()
    {
        var options = new RestClientOptions("https://endim2jwvq8mr.x.pipedream.net/");
        var client  = new RestClient(options);

        var request = new RestRequest("resource");

        request.AddHeader("Content-Type", "application/force-download");
        var response = await client.GetAsync(request);
    }
        /// <summary>
        /// Configure the client using the provided options
        /// </summary>
        /// <param name="exchangeOptions">Options</param>
        protected void Configure(RestClientOptions exchangeOptions)
        {
            RequestTimeout     = exchangeOptions.RequestTimeout;
            RateLimitBehaviour = exchangeOptions.RateLimitingBehaviour;
            var rateLimiters = new List <IRateLimiter>();

            foreach (var rateLimiter in exchangeOptions.RateLimiters)
            {
                rateLimiters.Add(rateLimiter);
            }
            RateLimiters = rateLimiters;
        }
    public MultipartFormDataTests(ITestOutputHelper output)
    {
        _output = output;
        _server = SimpleServer.Create(RequestHandler.Handle);

        var options = new RestClientOptions(_server.Url)
        {
            ConfigureMessageHandler = handler => new HttpTracerHandler(handler, new OutputLogger(output), HttpMessageParts.All)
        };

        _client = new RestClient(options);
    }
        private async static void GetMessageStatusCall(Guid messageId)
        {
            // Setup a RESTful client object using the message status URL with our API Space and message id incorporated
            var options = new RestClientOptions(string.Format("https://api.comapi.com/apispaces/{0}/messages/{1}", APISPACE, messageId.ToString("D")))
            {
                ThrowOnAnyError = false,
                Timeout         = 30000
            };

            var client = new RestClient(options);

            client.AddDefaultHeader("Content-Type", "application/json");
            client.AddDefaultHeader("Accept", "application/json");

            var request = new RestRequest();

            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("authorization", "Bearer " + TOKEN); // Add the security token

            // Make the web service call
            var response = await client.ExecuteGetAsync(request);

            switch (response.StatusCode)
            {
            case System.Net.HttpStatusCode.OK:
                // Sucess output the response body
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine(FormatJson(response.Content));
                Console.ForegroundColor = ConsoleColor.White;

                // Inspect the status
                dynamic statusObject = JsonConvert.DeserializeObject(response.Content);

                // Check to see if the message is delivered
                Console.WriteLine(string.Format("The message ({0}) is currently in the {1} status.", messageId.ToString("D"), statusObject.status));
                Console.WriteLine(string.Format("It was sent on the {0} channel.", statusObject.statusDetails.channel));

                Console.WriteLine(string.Empty);
                break;

            case System.Net.HttpStatusCode.NotFound:
                // Sucess output the response body
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(string.Format("The message ({0}) was not found!", messageId.ToString("D")));
                Console.ForegroundColor = ConsoleColor.White;
                break;

            default:
                // Something went wrong.
                throw new InvalidOperationException(string.Format("Call to Dotdigital Enterprise Communications API failed with status code ({0}), and body: {1}", response.StatusCode, response.Content));
            }
        }
    async Task <string> GetToken()
    {
        var options = new RestClientOptions(_baseUrl);

        using var client = new RestClient(options)
              {
                  Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret),
              };

        var request = new RestRequest("oauth2/token")
                      .AddParameter("grant_type", "client_credentials");
        var response = await client.PostAsync <TokenResponse>(request);

        return($"{response!.TokenType} {response!.AccessToken}");
    }
        public RunMyAccountsClient(string tenant, string apikey)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

            ApiKey = apikey;

            RestClientOptions option = new RestClientOptions("https://service.runmyaccounts.com/api/latest/clients/");

            option.Encoding = Encoding.UTF8;
            client          = new RestClient(option);
            client.UseSerializer(() => new NewtonsoftJsonSerializer());
            client.AddDefaultHeader("ContentType", "application/json");
            client.AddDefaultParameter("api_key", apikey, ParameterType.QueryString);
            client.AddDefaultParameter("tenant", tenant, ParameterType.UrlSegment);
        }
Exemple #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="baseurl"></param>
        /// <returns></returns>
        public RestClient CreateJsonBytesClient(string baseurl)
        {
            var _options = new RestClientOptions
            {
                BaseUrl   = new System.Uri(baseurl),
                Timeout   = 10 * 1000,
                UserAgent = __user_agent
            };

            var _client = new RestClient(_options);

            //_client.RemoveHandler(__content_type);
            //_client.AddHandler(__content_type, () => new RestSharpJsonNetDeserializer());

            return(_client);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="URLBase">Point at a different server</param>
        public APIClient(string URLBase = "https://www.calcbench.com/api")
        {
            var options = new RestClientOptions(URLBase)
            {
                ThrowOnAnyError = true,
            };

            if (URLBase != "https://www.calcbench.com/api")
            {
                options.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
            }

            client = new RestClient(options);

            client.UseNewtonsoftJson();
        }
        private async static void SendSMSBatch(SMSSendRequest[] smsRequests)
        {
            // Setup a REST client object using the message send URL with our API Space incorporated
            var options = new RestClientOptions(string.Format("https://api.comapi.com/apispaces/{0}/messages/batch", CUSTOMER_APISPACE))
            {
                ThrowOnAnyError = false,
                Timeout         = 30000
            };

            var client = new RestClient(options);

            client.AddDefaultHeader("Content-Type", "application/json");
            client.AddDefaultHeader("Accept", "application/json");

            var request = new RestRequest();

            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("authorization", "Bearer " +
                              CreateImpersonationToken(
                                  CUSTOMER_ACCOUNT_ID,
                                  RESELLER_ACCOUNT_ID,
                                  RESELLER_TOKEN_ISSUER,
                                  RESELLER_TOKEN_SECRET)); // Add the security token

            // Serialise our SMS request object to JSON for submission
            string requestJson = JsonConvert.SerializeObject(smsRequests, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            request.AddParameter("application/json", requestJson, ParameterType.RequestBody);

            // Make the web service call
            var response = await client.ExecutePostAsync(request);

            if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
            {
                // Something went wrong.
                throw new InvalidOperationException(string.Format("Call to Dotdigital Enterprise Communications API failed with status code ({0}), and body: {1}", response.StatusCode, response.Content));
            }
            else
            {
                // Sucess output the response body
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(FormatJson(response.Content));
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
        public static IServiceCollection AddDiscogsProvider(this IServiceCollection services, IConfiguration configuration)
        {
            var discogsSettings          = configuration.GetSection("DiscogsSettings").Get <DiscogsApiClientConfiguration>();
            var discogsSettingsValidator = new DiscogsApiClientConfigurationValidator();

            discogsSettingsValidator.ValidateAndThrow(discogsSettings);

            services.AddSingleton <IDiscogsApiClientConfiguration>(_ => discogsSettings);

            var restClientOptions = new RestClientOptions(discogsSettings.BaseUrl);
            var restClient        = new RestClient(restClientOptions);

            services.AddScoped <IDiscogsApiClient, DiscogsApiClient>(_ => new DiscogsApiClient(discogsSettings, restClient));
            services.AddScoped <IDiscogsProvider, DiscogsProvider>();

            return(services);
        }
Exemple #15
0
        public UpdatesService(PlatformService platform, ISettingsStorageService settingsStorage, SettingsService settings)
        {
            Platform        = platform;
            SettingsStorage = settingsStorage;
            Settings        = settings;
#if DEBUG
            var uri = new Uri("http://localhost:5000/");
#else
            var uri = new Uri("https://api.guerra24.net/");
#endif
            var options = new RestClientOptions(uri)
            {
                UserAgent = "LRReader"
            };
            client = new RestClient(options);
            client.UseNewtonsoftJson();
        }
Exemple #16
0
        public static IServiceCollection AddComicVineProvider(this IServiceCollection services, IConfiguration configuration)
        {
            var comicVineSettings          = configuration.GetSection("ComicVineSettings").Get <ComicVineApiClientConfiguration>();
            var comicVineSettingsValidator = new ComicVineApiClientConfigurationValidator();

            comicVineSettingsValidator.ValidateAndThrow(comicVineSettings);

            services.AddSingleton <IComicVineApiClientConfiguration>(comicVineSettings);

            var restClientOptions = new RestClientOptions(comicVineSettings.BaseUrl);
            var restClient        = new RestClient(restClientOptions);

            services.AddScoped <IComicVineApiClient, ComicVineApiClient>(_ => new ComicVineApiClient(comicVineSettings, restClient));
            services.AddScoped <IComicVineProvider, ComicVineProvider>();

            return(services);
        }
Exemple #17
0
        public static IServiceCollection AddBoardGameGeekProvider(this IServiceCollection services, IConfiguration configuration)
        {
            var boardGameGeekSettings          = configuration.GetSection("BoardGameGeekSettings").Get <BoardGameGeekApiClientConfiguration>();
            var boardGameGeekSettingsValidator = new BoardGameGeekApiClientConfigurationValidator();

            boardGameGeekSettingsValidator.ValidateAndThrow(boardGameGeekSettings);

            services.AddSingleton <IBoardGameGeekApiClientConfiguration>(boardGameGeekSettings);

            var restClientOptions = new RestClientOptions($"{boardGameGeekSettings.BaseUrl}{boardGameGeekSettings.ApiVersion}");
            var restClient        = new RestClient(restClientOptions);

            services.AddScoped <IBoardGameGeekApiClient, BoardGameGeekApiClient>(_ => new BoardGameGeekApiClient(boardGameGeekSettings, restClient));
            services.AddScoped <IBoardGameGeekProvider, BoardGameGeekProvider>();

            return(services);
        }
Exemple #18
0
    public RestClient(RestClientOptions options, Action <HttpRequestHeaders>?configureDefaultHeaders = null)
    {
        UseDefaultSerializers();

        Options            = options;
        CookieContainer    = Options.CookieContainer ?? new CookieContainer();
        _disposeHttpClient = true;

        var handler = new HttpClientHandler();

        ConfigureHttpMessageHandler(handler);

        var finalHandler = Options.ConfigureMessageHandler?.Invoke(handler) ?? handler;

        HttpClient = new HttpClient(finalHandler);
        ConfigureHttpClient(HttpClient);
        configureDefaultHeaders?.Invoke(HttpClient.DefaultRequestHeaders);
    }
Exemple #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="baseurl"></param>
        /// <returns></returns>
        public override RestClient CreateJsonClient(string baseurl)
        {
            var _options = new RestClientOptions
            {
                BaseUrl = new System.Uri(baseurl),
                Timeout = 5 * 1000,
                //ReadWriteTimeout = 32 * 1000,
                UserAgent = __user_agent,
                Encoding  = Encoding.GetEncoding(65001)
            };

            var _client = new RestClient(_options);

            //_client.RemoveHandler(__content_type);
            //_client.AddHandler(__content_type, () => new RestSharpJsonNetDeserializer());

            return(_client);
        }
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="exchangeName">The name of the exchange this client is for</param>
        /// <param name="exchangeOptions">The options for this client</param>
        /// <param name="authenticationProvider">The authentication provider for this client (can be null if no credentials are provided)</param>
        protected RestClient(string exchangeName, RestClientOptions exchangeOptions, AuthenticationProvider?authenticationProvider) : base(exchangeName, exchangeOptions, authenticationProvider)
        {
            if (exchangeOptions == null)
            {
                throw new ArgumentNullException(nameof(exchangeOptions));
            }

            RequestTimeout = exchangeOptions.RequestTimeout;
            RequestFactory.Configure(exchangeOptions.RequestTimeout, exchangeOptions.Proxy, exchangeOptions.HttpClient);
            RateLimitBehaviour = exchangeOptions.RateLimitingBehaviour;
            var rateLimiters = new List <IRateLimiter>();

            foreach (var rateLimiter in exchangeOptions.RateLimiters)
            {
                rateLimiters.Add(rateLimiter);
            }
            RateLimiters = rateLimiters;
        }
        private void GenerateTokenForInvalidIMSUser()
        {
            var restClientOptions = new RestClientOptions
            {
                BaseEndpoint  = _testCfg.ERApiEndpoint,
                TokenProvider = new ResourceOwnerFlow(
                    _testCfg.InvalidImsEndpoint,
                    _testCfg.ImsClientId,
                    _testCfg.InvalidImsClientSecret,
                    _testCfg.PrimaryUserName,
                    _testCfg.PrimaryUserPassword,
                    _testCfg.ImsScopes),
                RetryPolicy = new DefaultRetryPolicy()
            };
            var erRestClient = new RestClient(restClientOptions);

            scenarioContext.Set <IRestClient>(erRestClient, "InvalidIMSUser");
        }
    public static async Task Run()
    {
        var options = new RestClientOptions("https://api.muxiaoguo.cn/api/bad_or_luck")
        {
            ThrowOnAnyError = true,
            Timeout         = 1000
        };
        var client = new RestClient(options);

        var request = new RestRequest()
                      .AddQueryParameter("Num", "11111111111");

        var response = await client.PostAsync <MyResponse>(request, CancellationToken.None);

        Console.WriteLine(response?.Msg);
        Console.WriteLine(response?.Data?.Analysis);
        Console.WriteLine(response?.Data?.BadORluck);
    }
Exemple #23
0
        public void GivenAnIMSUserWithAnAccessToken(string userName)
        {
            var restClientOptions = new RestClientOptions
            {
                BaseEndpoint  = _testCfg.ERApiEndpoint,
                TokenProvider = new ResourceOwnerFlow(
                    _testCfg.ImsEndpoint,
                    _testCfg.ImsClientId,
                    _testCfg.ImsClientSecret,
                    _testCfg.PrimaryUserName,
                    _testCfg.PrimaryUserPassword,
                    _testCfg.ImsScopes),
                RetryPolicy = new DefaultRetryPolicy()
            };
            var erRestClient = new RestClient(restClientOptions);

            scenarioContext.Set <IRestClient>(erRestClient, "PrimaryIMSUser");
        }
        public static IServiceCollection AddGiantBombProvider(this IServiceCollection services, IConfiguration configuration)
        {
            var giantBombSettings          = configuration.GetSection("GiantBombSettings").Get <GiantBombApiClientConfiguration>();
            var giantBombSettingsValidator = new GiantBombApiClientConfigurationValidator();

            giantBombSettingsValidator.ValidateAndThrow(giantBombSettings);

            services.AddSingleton <IGiantBombApiClientConfiguration>(giantBombSettings);

            var restClientOptions = new RestClientOptions(giantBombSettings.BaseUrl);
            var restClient        = new RestClient(restClientOptions);

            restClient.UseNewtonsoftJson();

            services.AddScoped <IGiantBombApiClient, GiantBombApiClient>(_ => new GiantBombApiClient(giantBombSettings, restClient));
            services.AddScoped <IGiantBombProvider, GiantBombProvider>();

            return(services);
        }
Exemple #25
0
        public static IServiceCollection AddMovieDatabaseProvider(this IServiceCollection services, IConfiguration configuration)
        {
            var movieDatabaseSettings          = configuration.GetSection("MovieDatabaseSettings").Get <MovieDatabaseApiClientConfiguration>();
            var movieDatabaseSettingsValidator = new MovieDatabaseApiClientConfigurationValidator();

            movieDatabaseSettingsValidator.ValidateAndThrow(movieDatabaseSettings);

            services.AddSingleton <IMovieDatabaseApiClientConfiguration>(movieDatabaseSettings);

            var restClientOptions = new RestClientOptions(movieDatabaseSettings.BaseUrl);
            var restClient        = new RestClient(restClientOptions);

            restClient.UseNewtonsoftJson();

            services.AddScoped <IMovieDatabaseApiClient, MovieDatabaseApiClient>(_ => new MovieDatabaseApiClient(movieDatabaseSettings, restClient));
            services.AddScoped <IMovieDatabaseProvider, MovieDatabaseProvider>();

            return(services);
        }
Exemple #26
0
        public bool RefreshSettings(ServerProfile profile)
        {
            if (!Uri.IsWellFormedUriString(profile.ServerAddress, UriKind.Absolute))
            {
                return(false);
            }
            var options = new RestClientOptions(profile.ServerAddress)
            {
                UserAgent = "LRReader"
            };

            Client = new RestClient(options);
            Client.UseNewtonsoftJson();
            if (!string.IsNullOrEmpty(profile.ServerApiKey))
            {
                var base64Key = Convert.ToBase64String(Encoding.UTF8.GetBytes(profile.ServerApiKey));
                Client.AddDefaultHeader("Authorization", $"Bearer {base64Key}");
            }
            return(true);
        }
Exemple #27
0
        public ImgurClient(string clientId)
        {
            var options = new RestClientOptions(ImgurApiUrl)
            {
                ThrowOnAnyError = true,
                FollowRedirects = true,
                PreAuthenticate = true,
                MaxTimeout      = 20 * 1000,
                //Proxy = new WebProxy("http://localhost:8080"),
                ConfigureMessageHandler = orig =>
                {
                    _rateLimitHandler = new RateLimitHandler(orig);
                    return(_rateLimitHandler);
                }
            };

            _client = new RestClient(options);
            _client.UseAuthenticator(new ImgurAuthenticator(clientId));
            _client.UseNewtonsoftJson();
        }
Exemple #28
0
    public RestClient(HttpClient httpClient, RestClientOptions?options = null, bool disposeHttpClient = false)
    {
        if (options?.CookieContainer != null)
        {
            throw new ArgumentException("Custom cookie container cannot be added to the HttpClient instance", nameof(options.CookieContainer));
        }

        UseDefaultSerializers();

        HttpClient         = httpClient;
        Options            = options ?? new RestClientOptions();
        CookieContainer    = new CookieContainer();
        _disposeHttpClient = disposeHttpClient;

        if (httpClient.BaseAddress != null && Options.BaseUrl == null)
        {
            Options.BaseUrl = httpClient.BaseAddress;
        }

        ConfigureHttpClient(HttpClient);
    }
Exemple #29
0
    public NStackRepository(NStackConfiguration configuration)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }

        if (string.IsNullOrWhiteSpace(configuration.ApiKey))
        {
            throw new ArgumentNullException(configuration.ApiKey);
        }

        if (string.IsNullOrWhiteSpace(configuration.ApplicationId))
        {
            throw new ArgumentNullException(configuration.ApplicationId);
        }

        if (string.IsNullOrWhiteSpace(configuration.BaseUrl))
        {
            throw new ArgumentNullException(configuration.BaseUrl);
        }

        var options = new RestClientOptions(configuration.BaseUrl);

        Client = new RestClient(options);
        Client.UseSystemTextJson(new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true,
            Converters =
            {
                new JsonStringEnumConverter()
            }
        });

        Client.AddDefaultHeaders(new Dictionary <string, string>
        {
            { "X-Application-Id", configuration.ApplicationId },
            { "X-Rest-Api-Key", configuration.ApiKey }
        });
    }
Exemple #30
0
        /// <summary>
        /// Create OpenStack API client.
        /// </summary>
        /// <param name="openStackAddress">OpenStack address..</param>
        public OpenStack(string openStackAddress)
        {
            _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            if (string.IsNullOrEmpty(openStackAddress))
            {
                throw new OpenStackAPIException("Not specify URL address for OpenStack");
            }

            var options = new RestClientOptions($"{openStackAddress}:{OpenStackSettings.IdentityPort}/")
            {
                Encoding    = Encoding.UTF8,
                CachePolicy = new CacheControlHeaderValue()
                {
                    NoCache = true,
                    NoStore = true
                },
                Timeout = OpenStackSettings.ConnectionTimeout
            };

            _basicRestClient = new RestClient(options);
        }