コード例 #1
0
        private static IRestClient BuildRestClient()
        {
            string      url        = ConfigurationManager.AppSettings["OpenWeatherMapUrl"];
            string      appId      = ConfigurationManager.AppSettings["AppId"];
            IRestClient restClient = new RestClient(url);

            restClient.AddDefaultParameter(QueryConstants.ApiKey, appId);
            return(restClient);
        }
コード例 #2
0
        /// <summary>
        /// Create a new Rest client with your API token and custom base URL
        /// </summary>
        /// <param name="apiToken">Your secret API token</param>
        /// <param name="baseUrl">The base API URL, for example, pre-release API versions</param>
        public GiantBombRestClient(string apiToken, Uri baseUrl)
        {
            BaseUrl = baseUrl.ToString();
            ApiKey  = apiToken;

            var version = typeof(GiantBombRestClient).GetTypeInfo().Assembly.GetName().Version;

            _client = new RestClient
            {
                UserAgent = "giantbomb-csharp/" + version,
                BaseUrl   = baseUrl
            };

            // API token is used on every request
            _client.AddDefaultParameter("api_key", ApiKey);
            _client.AddDefaultParameter("format", "json");
            _client.UseSerializer(() => new GiantBombDeserializer());
        }
コード例 #3
0
ファイル: IndexModule.cs プロジェクト: mbmccormick/HappyHour
        public IndexModule()
        {
            Get["/api/v1/venues"] = parameters =>
            {
                RestClient client = new RestClient("https://api.foursquare.com/v2");
                client.AddDefaultParameter("client_id", "VJDTI5JLMM1LL2Z0TP3XZQF515KKKQ5SHAAHVX2SBGBKCWE0");
                client.AddDefaultParameter("client_secret", "GQVAJXFFFSBXVTP2P2DGL2MR1NUQ0HOGKA3OKNGJSJ31MPIO");

                RestRequest request = new RestRequest("/venues/explore");
                request.AddParameter("ll", Request.Query.location);
                request.AddParameter("query", "happy hour");

                var response = client.Execute <Models.Response>(request);

                var data = response.Data.response;

                return(Response.AsJson(data));
            };
        }
コード例 #4
0
        /// <summary>
        /// Creates a new rest client for the Mollie API
        /// </summary>
        private RestClient CreateRestClient()
        {
            RestClient restClient = new RestClient();

            restClient.BaseUrl = this.GetBaseAddress();
            restClient.AddDefaultHeader("Content-Type", "application/json");
            restClient.AddDefaultParameter("Authorization", $"Bearer {this._apiKey}", ParameterType.HttpHeader);

            return(restClient);
        }
コード例 #5
0
        RestClient PrepareRestClient(string accessToken)
        {
            var restClient = new RestClient(WIT_API_HOST);

            restClient.AddDefaultHeader("Authorization", $"Bearer {accessToken}");
            restClient.AddDefaultHeader("Content-Type", "application/json");
            restClient.AddDefaultHeader("Accept", "application/json");
            restClient.AddDefaultParameter("v", WIT_API_VERSION, ParameterType.QueryString);

            return(restClient);
        }
        public GoogleMapsGeocodingService(IConfiguration config)
        {
            GoogleMapsClient = new RestClient
            {
                BaseUrl = new Uri("https://maps.googleapis.com")
            };

            var apiKey = config["GoogleMapsApiKey"];

            GoogleMapsClient.AddDefaultParameter("key", apiKey, ParameterType.QueryString);
        }
コード例 #7
0
ファイル: TMDBService.cs プロジェクト: milten21/TMDBMobile
        public TMDBService(IConfigurationService configurationService)
        {
            ConfigurationService = configurationService;

            RestClient = new RestClient
            {
                BaseUrl = new Uri(ConfigurationService.ApiUrl)
            };

            RestClient.AddDefaultParameter("api_key", ConfigurationService.ApiKey, ParameterType.QueryString);
        }
コード例 #8
0
        public static RestClient CreateComicVineClient(string ComicVineApiKey)
        {
            RestClient _Client = new RestClient(COMICVINE_API_URL);

            _Client.AddDefaultParameter(new Parameter()
            {
                Name = "api_key", Type = ParameterType.QueryString, Value = ComicVineApiKey
            });

            return(_Client);
        }
コード例 #9
0
ファイル: TextService.cs プロジェクト: zachary-kaelan/CSharp
        public TextService(string userName, string password, string countryCode)
        {
            client = new RestClient("https://api.zipwhip.com/");
            RestRequest request = new RestRequest("user/login", Method.GET);

            request.AddParameter("password", password);
            request.AddParameter("remember", "true");
            IRestResponse <UserSession> response = client.Execute <UserSession>(request);

            this.session = response.Data.response;
            client.AddDefaultParameter("session", session);
        }
コード例 #10
0
        /// <summary>
        /// Returns a client object with the default values, virtual for testability
        /// </summary>
        /// <param name="url">The API endpoint you are hitting</param>
        /// <returns></returns>
        protected virtual IRestClient GetClient(string url)
        {
            var client = new RestClient()
            {
                Timeout = this.Timeout, BaseUrl = "https://" + Subdomain + ".pagerduty.com/api" + url
            };

            client.AddDefaultParameter(new Parameter {
                Name = "Authorization", Value = "Token token=" + this.AccessToken, Type = ParameterType.HttpHeader
            });
            return(client);
        }
コード例 #11
0
        public void TestOnlyDefaultParameter()
        {
            using (var client = new RestClient("http://localhost"))
            {
                client.AddDefaultParameter("param1", "value1");

                var request = new RestRequest();

                var uri = client.BuildUri(request).ToString();
                Assert.Equal("http://localhost/?param1=value1", uri);
            }
        }
コード例 #12
0
        public void TestOnlyDefaultParameter()
        {
            using (var client = new RestClient("http://localhost"))
            {
                client.AddDefaultParameter("param1", "value1");

                var request = new RestRequest();

                var uri = client.BuildUri(request).ToString();
                Assert.Equal("http://localhost/?param1=value1", uri);
            }
        }
コード例 #13
0
        public static IRestClient CreateClient(ViaTimConnectionSettings accessInfo)
        {
            var baseUrl = BuildUri(accessInfo.ApiUrl);

            var client = new RestClient(baseUrl);

            if (!string.IsNullOrEmpty(accessInfo.ApiKey))
            {
                client.AddDefaultParameter("x-auth-token", accessInfo.ApiKey, ParameterType.HttpHeader);
            }

            return(client);
        }
コード例 #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GoodreadsClient"/> class.
        /// Use this constructor if you already have OAuth permissions for the user.
        /// </summary>
        /// <param name="apiKey">Your Goodreads API key.</param>
        /// <param name="apiSecret">Your Goodreads API secret.</param>
        /// <param name="accessToken">The user's OAuth access token.</param>
        /// <param name="accessSecret">The user's OAuth access secret.</param>
        public GoodreadsClient(string apiKey, string apiSecret, string accessToken, string accessSecret)
        {
            var client = new RestClient(new Uri(GoodreadsUrl))
            {
                UserAgent = "goodreads-dotnet"
            };

            client.AddDefaultParameter("key", apiKey, ParameterType.QueryString);
            client.AddDefaultParameter("format", "xml", ParameterType.QueryString);

            var apiCredentials = new ApiCredentials(client, apiKey, apiSecret, accessToken, accessSecret);

            // Setup the OAuth authenticator if they have passed on the appropriate tokens
            if (!string.IsNullOrWhiteSpace(accessToken) &&
                !string.IsNullOrWhiteSpace(accessSecret))
            {
                client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                    apiKey, apiSecret, accessToken, accessSecret);
            }

            Connection       = new Connection(client, apiCredentials);
            Authors          = new AuthorsClient(Connection);
            Books            = new BooksClient(Connection);
            Shelves          = new ShelvesClient(Connection);
            Users            = new UsersClient(Connection);
            Reviews          = new ReviewsClient(Connection);
            Series           = new SeriesClient(Connection);
            AuthorsFollowing = new AuthorsFollowingClient(Connection);
            Events           = new EventsClient(Connection);
            Followers        = new FollowersClient(Connection);
            Friends          = new FriendsClient(Connection);
            Notifications    = new NotificationsClient(Connection);
            Groups           = new GroupClient(Connection);
            Quotes           = new QuotesClient(Connection);
            UserStatuses     = new UserStatusesClient(Connection);
            Updates          = new UpdatesClient(Connection);
            Recommendations  = new RecommendationsClient(Connection);
            ReadStatuses     = new ReadStatusesClient(Connection);
        }
コード例 #15
0
        private static IRestClient CreateClient(ApiCredentials credentials)
        {
            var client = new RestClient(new Uri(GoodreadsUrl))
            {
                UserAgent = GoodreadsUserAgent
            };

            client.AddDefaultParameter("key", credentials.ApiKey, ParameterType.QueryString);
            client.AddDefaultParameter("format", "xml", ParameterType.QueryString);

            if (!string.IsNullOrEmpty(credentials.OAuthToken) && !string.IsNullOrEmpty(credentials.OAuthTokenSecret))
            {
                client.Authenticator =
                    OAuth1Authenticator.ForProtectedResource(
                        credentials.ApiKey,
                        credentials.ApiSecret,
                        credentials.OAuthToken,
                        credentials.OAuthTokenSecret);
            }

            return(client);
        }
コード例 #16
0
        public SlackClient(string clientid, string clientSecret, string oauth, string veriftoken)
        {
            OAuthToken   = oauth;
            VerifToken   = veriftoken;
            ClientID     = clientid;
            ClientSecret = clientSecret;

            failed     = 0;
            exceptions = new List <Exception>();

            queueCount = 0;
            Handles    = new ConcurrentQueue <RestRequestAsyncHandle>();
            results    = new Dictionary <string, ConcurrentQueue <Dictionary <string, object> > >();
            client     = new RestClient("https://slack.com/api/");
            client.AddDefaultParameter("token", OAuthToken, ParameterType.QueryString);
            client.AddDefaultHeader("Authorization", "Bearer " + OAuthToken);

            ServicePointManager.UseNagleAlgorithm = false;
            waitThread = new Thread(HandlesHandler);
            waitThread.Start();


            /*.OrderBy(f => f.created);
             *
             * foreach (var file in fileObjs)
             * {
             *  Console.WriteLine(file.name);
             *  Console.WriteLine("   Created: \t" + UnixTime.AddSeconds(Convert.ToDouble(file.created)).ToString("d"));
             *  Console.WriteLine("   SlackFileType: \t" + file.filetype);
             *  Console.WriteLine("   Size: \t{0}", file.size);
             *  Console.WriteLine("   URL: \t{0}", file.url_private);
             *  Console.WriteLine();
             * }
             */

            /*
             * this.results["files.list"].TryDequeue(out Dictionary<string, object> files);
             * var fileObjs = JSON.Deserialize<List<Dictionary<string, object>>>(files["files"].ToString(), Options.ExcludeNullsIncludeInheritedCamelCase).OrderBy(f => C<int>(f["created"]));
             *
             * foreach(var file in fileObjs)
             * {
             *  Console.WriteLine(C<string>(file["name"]));
             *  Console.WriteLine("   Created: \t" + UnixTime.AddSeconds(Convert.ToDouble(C<int>(file["created"]))).ToString("d"));
             *  Console.WriteLine("   SlackFileType: \t" + C<string>(file["filetype"]));
             *  Console.WriteLine("   Size: \t{0}", C<long>(file["size"]));
             *  Console.WriteLine();
             * }
             */
        }
コード例 #17
0
        private IRestClient CreateClient()
        {
            var restClient = new RestClient();

            restClient.BaseUrl = _baseUrl;

            restClient.ClearHandlers();
            restClient.AddHandler("*", new ConnectConverter(UDAPI.Configuration.ContentType));

            if (_xAuthTokenParameter != null)
            {
                restClient.AddDefaultParameter(_xAuthTokenParameter);
            }
            return(restClient);
        }
コード例 #18
0
        public void TestParameterOverride()
        {
            using (var client = new RestClient("http://localhost"))
            {
                client.AddDefaultParameter("param1", "value1");

                var request = new RestRequest();
                request
                    .AddParameter("param2", "value2")
                    .AddOrUpdateParameter("param1", "value1.1");

                var uri = client.BuildUri(request).ToString();
                Assert.Equal("http://localhost/?param1=value1.1&param2=value2", uri);
            }
        }
コード例 #19
0
        public async Task TestDefaultParameter()
        {
            using (var client = new RestClient("http://httpbin.org/"))
            {
                client.AddDefaultParameter("Restsharp-Test2", "TestValue2", ParameterType.HttpHeader);

                var request = new RestRequest("post", HttpMethod.Post);
                request.AddParameter("param1", "ParamValue1");

                var response = await client.Execute <Response>(request);

                Assert.Equal("ParamValue1", response.Data.Form["param1"]);
                Assert.Equal("TestValue2", response.Data.Headers["Restsharp-Test2"]);
            }
        }
コード例 #20
0
        public void TestParameterOverride()
        {
            using (var client = new RestClient("http://localhost"))
            {
                client.AddDefaultParameter("param1", "value1");

                var request = new RestRequest();
                request
                .AddParameter("param2", "value2")
                .AddOrUpdateParameter("param1", "value1.1");

                var uri = client.BuildUri(request).ToString();
                Assert.Equal("http://localhost/?param1=value1.1&param2=value2", uri);
            }
        }
コード例 #21
0
        private IRestClient CreateClient()
        {
            var restClient = new RestClient();

            restClient.BaseUrl = BaseUrl;

            restClient.ClearHandlers();
            restClient.AddHandler("*", () => new ConnectConverter(UDAPI.Configuration.ContentType));

            if (!string.IsNullOrEmpty(SessionToken))
            {
                restClient.AddDefaultParameter(XAuthToken, SessionToken);
            }
            return(restClient);
        }
コード例 #22
0
 public static void AddDefaultHeaders(this RestClient paramRestClient)
 {
     paramRestClient.RemoveDefaultParameter("Accept");
     paramRestClient.AddDefaultParameter("Accept", "application/json", ParameterType.HttpHeader);
     paramRestClient.AddDefaultParameter("ce_ipaddress", String.Join(",", Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(paramX => paramX.AddressFamily == AddressFamily.InterNetwork).Select(paramX => paramX.ToString())), ParameterType.HttpHeader);
     paramRestClient.AddDefaultParameter("ce_hostname", Dns.GetHostName(), ParameterType.HttpHeader);
     paramRestClient.AddDefaultParameter("ce_version", Assembly.GetExecutingAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion, ParameterType.HttpHeader);
     paramRestClient.AddDefaultParameter("ce_id", TerodoViewApiBase.CeId, ParameterType.HttpHeader);
     paramRestClient.AddDefaultParameter("ce_organization_id", TerodoViewApiBase.OrganizationID, ParameterType.HttpHeader);
 }
コード例 #23
0
        public HttpResponseMessage Get()
        {
            var client = new RestClient()
            {
                Timeout = 10000, BaseUrl = new System.Uri("https://<subdomain>.pagerduty.com/api/")
            };

            client.AddDefaultParameter(new Parameter {
                Name = "Authorization", Value = "Token token=<token>", Type = ParameterType.HttpHeader
            });

            var onCallRequest = new RestRequest("v1/escalation_policies/on_call", Method.GET);

            IRestResponse onCallResponse  = client.Execute(onCallRequest);
            var           content         = onCallResponse.Content;
            dynamic       pagerDutyOnCall = JsonConvert.DeserializeObject(content);
            dynamic       user            = pagerDutyOnCall.escalation_policies[0].escalation_rules[0].rule_object;

            User userObject = new Models.User();

            userObject.id    = user.id;
            userObject.name  = user.name;
            userObject.email = user.email;

            var userRequest = new RestRequest("v1/users/" + userObject.id + "/contact_methods", Method.GET);

            IRestResponse userResponse  = client.Execute(userRequest);
            var           userDetails   = userResponse.Content;
            dynamic       userMobile    = JsonConvert.DeserializeObject(userDetails);
            var           contactCounts = userMobile.contact_methods.Count;

            for (int i = 0; i < contactCounts; i++)
            {
                if (userMobile.contact_methods[i].type == "phone")
                {
                    userObject.mobile = "+" + userMobile.contact_methods[i].country_code + userMobile.contact_methods[i].address;
                }
            }


            var twilioResponse = new TwilioResponse();

            twilioResponse.Say("Welcome to the Support Centre. Please wait while we route your call.");
            twilioResponse.Dial(userObject.mobile);


            return(this.Request.CreateResponse(HttpStatusCode.OK, twilioResponse.Element, new XmlMediaTypeFormatter()));
        }
コード例 #24
0
        public void ModuleInitialize(SACInitialize initialize)
        {
            Logger = initialize.Logger;

            HttpClient = new RestClient();
            HttpClient.AddDefaultParameter("json", 0);

            Config = new ConfigManager <Configuration>(initialize.ConfigurationPath, "config.json", new Configuration(), Sync);
            if (!Config.Load())
            {
                Logger.Warn("Cannot load config. You probably need to configure new one.");
                Config.Save();
            }

            Window = new ConfigurationForm();
        }
コード例 #25
0
        /**
         * This method return the gamelist representing the id64 key
         */
        private IEnumerable <Game> GetGameList(long id64)
        {
            const string baseUrl      = "http://api.steampowered.com";
            const string ressourceUrl = "IPlayerService/GetOwnedGames/v0001";
            var          restClient   = new RestClient(baseUrl);

            restClient.AddDefaultParameter("key", ApiKey);
            var restRequest = new RestRequest(ressourceUrl);

            restRequest.AddQueryParameter("steamid", "" + id64);
            restRequest.AddQueryParameter("format", "json");
            restRequest.AddQueryParameter("include_appinfo", "1");
            var response = restClient.Execute <RootObject>(restRequest);

            return(response.Data.response.games);
        }
コード例 #26
0
ファイル: Youtube.cs プロジェクト: zachary-kaelan/CSharp
        public List <VideoListModel> GetWatchHistory()
        {
            Page page = JSON.Deserialize <IEnumerable <Page> >(
                client.Execute(
                    new RestRequest(
                        "feed/history?pbj=1",
                        Method.GET
                        )
                    ).Content
                ).Last();

            client.AddDefaultParameter("session_token", page.xsrf_token, ParameterType.GetOrPost);

            ItemSectionRenderer   temp   = page.response.contents.twoColumnBrowserResultsRenderer.tabs.tabRenderer.content.sectionListRenderer.contents.itemSectionRenderer;
            List <VideoListModel> videos = new List <VideoListModel>(
                temp.contents.Select(v => v.Simplify())
                );

            page = new Page();

            ItemSectionRenderer GetItemSectionRenderer(RestRequest request)
            {
                return(JSON.Deserialize <IEnumerable <Page> >(
                           client.Execute(request).Content
                           ).Last().response.contents.twoColumnBrowserResultsRenderer.tabs.tabRenderer.content.sectionListRenderer.contents.itemSectionRenderer);
            }

            bool check = true;

            do
            {
                try
                {
                    RestRequest request = new RestRequest("browse_ajax", Method.POST);
                    request.AddParameter("ctoken", temp.continuations.nextContinuationData.continuation, ParameterType.QueryString);
                    request.AddParameter("itct", temp.continuations.nextContinuationData.clickTrackingParams, ParameterType.QueryString);
                    temp = GetItemSectionRenderer(request);
                    videos.AddRange(temp.contents.Select(v => v.Simplify()));
                }
                catch (Exception e)
                {
                    check = false;
                }
            } while (check && temp.contents != null && temp.contents.Any());

            return(videos);
        }
コード例 #27
0
        private T Execute <T>(RestRequest request) where T : new()
        {
            var client = new RestClient(BaseUrl);

            client.ClearHandlers();
            client.AddHandler("application/json", new JsonDeserializer());
            client.AddDefaultParameter("Accept-Encoding", "gzip,deflate", ParameterType.HttpHeader);

            request.AddParameter("apiKey", ApiKey);
            request.AddParameter("cid", Cid);
            request.AddParameter("minorRev", MinorRev);
            request.AddParameter("currencyCode", CurrencyCode);
            request.AddParameter("locale", Locale);
            request.AddParameter("sig", Sig);

            if (CustomerUserAgent.HasValue())
            {
                request.AddParameter("customerUserAgent", CustomerUserAgent);
            }

            if (CustomerSessionId.HasValue())
            {
                request.AddParameter("customerSessionId", CustomerSessionId);
            }

            if (CustomerIpAddress.HasValue())
            {
                request.AddParameter("customerIpAddress", CustomerIpAddress);
            }

            request.Parameters.ForEach(p => Debug.WriteLine(p.Name + "=" + p.Value));

            // This is a fix for the RestSharp Deserialiser
            // Not a long term fix
            // Better to migrate from RestSharp Json Deserialiser to Json.NET Deserialiser
            // and decorate our classes with properties
            request.OnBeforeDeserialization = removeAttributeSymbol;

            var response = client.Execute <T>(request);

            if (response.ErrorException != null)
            {
                throw response.ErrorException;
            }

            return(response.Data);
        }
コード例 #28
0
ファイル: Commands.cs プロジェクト: Stanley1551/KomobotV2
        private static async Task <string> GetAuthTokenFromBlizzard()
        {
            var url = Program.config.blizzardOauthAccessTokenEndpoint;

            var client = new RestClient(url);

            client.AddDefaultParameter("grant_type", "client_credentials");
            var request = new RestRequest(Method.POST);

            request.AddHeader("cache-control", "no-cache");
            request.AddParameter("client_id", Program.config.client_id);
            request.AddParameter("client_secret", Program.config.client_secret);

            var respone = await client.ExecuteTaskAsync(request);

            return(JsonConvert.DeserializeObject <AccessTokenResponse>(respone.Content).access_token);
        }
コード例 #29
0
        public async Task TestDefaultParameter(Type factoryType)
        {
            using (var client = new RestClient("http://httpbin.org/")
            {
                HttpClientFactory = CreateClientFactory(factoryType, false),
            })
            {
                client.AddDefaultParameter("Restsharp-Test2", "TestValue2", ParameterType.HttpHeader);

                var request = new RestRequest("post", Method.POST);
                request.AddParameter("param1", "ParamValue1");

                var response = await client.Execute<HttpBinResponse>(request);
                Assert.Equal("ParamValue1", response.Data.Form["param1"]);
                Assert.Equal("TestValue2", response.Data.Headers["Restsharp-Test2"]);
            }
        }
コード例 #30
0
        public async Task GetFormattedAddressFromCoordinate()
        {
            var    client = new RestClient("http://dev.virtualearth.net/REST/v1/");
            string key    = CredentialStore.RetrieveObject("bing.key.json").Key;

            client.AddDefaultParameter("key", key);

            dynamic proxy  = new RestSharpProxy(client);
            var     result = await proxy.Locations("44.9108238220215,-93.1702041625977").get(includeEntityTypes: "Address,PopulatedPlace,Postcode1,AdminDivision1,CountryRegion");

            Assert.AreEqual(200, (int)result.statusCode);
            Assert.IsTrue(result.resourceSets.Count > 0);
            Assert.IsTrue(result.resourceSets[0].resources.Count > 0);

            var address = result.resourceSets[0].resources[0].address.formattedAddress;

            Assert.AreEqual("1012 Davern St, St Paul, MN 55116", (string)address);
        }
コード例 #31
0
        public void TestParameterCaseInsensitive()
        {
            using (var client = new RestClient("http://localhost")
            {
                DefaultParameterNameComparer = StringComparer.OrdinalIgnoreCase,
            })
            {
                client.AddDefaultParameter("param1", "value1");

                var request = new RestRequest();
                request
                    .AddParameter("param2", "value2")
                    .AddParameter("Param1", "value1.1");

                var uri = client.BuildUri(request).ToString();
                Assert.Equal("http://localhost/?Param1=value1.1&param2=value2", uri);
            }
        }
コード例 #32
0
        public async Task TestDefaultParameter(Type factoryType)
        {
            using (var client = new RestClient("http://httpbin.org/")
            {
                HttpClientFactory = CreateClientFactory(factoryType, false),
            })
            {
                client.AddDefaultParameter("Restsharp-Test2", "TestValue2", ParameterType.HttpHeader);

                var request = new RestRequest("post", Method.POST);
                request.AddParameter("param1", "ParamValue1");

                var response = await client.Execute <HttpBinResponse>(request).ConfigureAwait(false);

                Assert.Equal("ParamValue1", response.Data.Form["param1"]);
                Assert.Equal("TestValue2", response.Data.Headers["Restsharp-Test2"]);
            }
        }
コード例 #33
0
ファイル: Core.cs プロジェクト: NoNST0P/SMS-Voice-dotnetSDK
        /// <summary>
        /// Initialize Rest client
        /// </summary>
        /// <param name="appSid"></param>
        /// <param name="baseUrl"></param>
        protected UnifonicClient(string appSid, string baseUrl)
        {
            BaseUrl = baseUrl;
            AppSid  = appSid;

            var          assembly     = Assembly.GetExecutingAssembly();
            AssemblyName assemblyName = new AssemblyName(assembly.FullName);
            var          version      = assemblyName.Version;

            Client = new RestClient
            {
                UserAgent = "unifonic-csharp/" + version + " (.NET " + Environment.Version + ")",
                BaseUrl   = new Uri(BaseUrl),
                Timeout   = 60000
            };
            Client.AddHandler("text/html", new JsonDeserializer());
            Client.AddDefaultParameter("AppSid", AppSid);
        }
コード例 #34
0
        public void TestParameterCaseInsensitive()
        {
            using (var client = new RestClient("http://localhost")
            {
                DefaultParameterNameComparer = StringComparer.OrdinalIgnoreCase,
            })
            {
                client.AddDefaultParameter("param1", "value1");

                var request = new RestRequest();
                request
                .AddParameter("param2", "value2")
                .AddParameter("Param1", "value1.1");

                var uri = client.BuildUri(request).ToString();
                Assert.Equal("http://localhost/?Param1=value1.1&param2=value2", uri);
            }
        }