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); }
/// <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()); }
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)); }; }
/// <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); }
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); }
public TMDBService(IConfigurationService configurationService) { ConfigurationService = configurationService; RestClient = new RestClient { BaseUrl = new Uri(ConfigurationService.ApiUrl) }; RestClient.AddDefaultParameter("api_key", ConfigurationService.ApiKey, ParameterType.QueryString); }
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); }
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); }
/// <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); }
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); } }
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); }
/// <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); }
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); }
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(); * } */ }
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); }
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¶m2=value2", uri); } }
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"]); } }
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); }
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); }
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())); }
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(); }
/** * 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); }
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); }
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); }
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); }
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"]); } }
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); }
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¶m2=value2", uri); } }
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"]); } }
/// <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); }