private void getTokens() { Models.AppData appdata = App.Database.GetAppDataAsync().Result; string deviceid = ""; if (appdata != null) { deviceid = appdata.DeviceID; } var client = new RestClient("https://www.kresgefor98.com/rest/CFCandidate/"); client.AddDefaultHeader("Content-type", "application/json"); var request = new RestRequest("token", Method.POST); var requestbody = new { deviceid = deviceid }; request.RequestFormat = DataFormat.Json; request.AddJsonBody(requestbody); var response = client.Execute(request); var newappdata = JsonConvert.DeserializeObject <Models.AppData>(response.Content); if (deviceid.Length > 0) { newappdata.DeviceID = deviceid; } App.Database.UpdateAppData(newappdata); access_token = newappdata.Access_Token; expires_in = newappdata.Expires_In; }
public UtahRealEstateReader() { _restClient = new RestClient(_uri); _restClient.CookieContainer = new CookieContainer(); _restClient.UserAgent = userAgent; _restClient.AddDefaultHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); _restClient.AddDefaultHeader("Accept-Language", language); var request = new RestRequest("index/public.index", Method.GET); var response = _restClient.Execute(request); var browserSession = new Cookie("ureBrowserSession", DateTime.Now.Ticks.ToString(), "/", host); _restClient.CookieContainer.Add(browserSession); }
static void Main(string[] args) { string token = args[1]; var accountName = args[0]; var client = new RestClient("https://ci.appveyor.com/"); client.AddDefaultHeader("Authorization", $"Bearer {token}"); var request = new RestRequest("/api/projects", Method.GET); var response = client.Execute <List <Project> >(request); List <Build> allBuilds = new List <Build>(); foreach (var project in response.Data) { Console.WriteLine($"Retrieving history for {project.Name}"); var historyRequest = new RestRequest($"/api/projects/{accountName}/{project.Slug}/history", Method.GET); historyRequest.AddParameter("recordsNumber", 100000); var history = client.Execute <History>(historyRequest).Data; allBuilds.AddRange(history.Builds.Where(b => b.Elapsed > TimeSpan.Zero)); } var buildsLastMonth = allBuilds.Where(b => b.Started >= DateTime.Now - TimeSpan.FromDays(30)); var timespan = buildsLastMonth .Aggregate(TimeSpan.Zero, (t1, t2) => t1 + t2.Elapsed); Console.WriteLine($"Spent {timespan.TotalMinutes} minutes over last 30 days"); }
public WebService() { var url = App.Locator.MainViewModel.ApiUrl; client = new RestClient(url); client.AddDefaultHeader("Accept", "application/json"); }
public IActionResult EditPost(DuracionTurnosDTO duracionTurnosDTO) { var client = new RestClient("https://localhost:44331/api/DuracionTurnos"); client.AddDefaultHeader("Content-type", "application/json"); var request1 = new RestRequest("https://localhost:44331/api/DuracionTurnos/" + duracionTurnosDTO.IdDuracionTurno, Method.PUT); request1.RequestFormat = DataFormat.Json; request1.AddJsonBody(duracionTurnosDTO); var response = client.Execute(request1); //grabo!!!! ////consumo la webapi para obtener los dtos //var cliente = new RestSharp.RestClient("https://localhost:44331/api/DuracionTurnos"); //var request = new RestSharp.RestRequest(RestSharp.Method.GET); //var dtos = cliente.Execute<List<DuracionTurnosDTO>>(request).Data;\ //consumo la webapi para obtener los dtos //como hago para simplemente ir al controlador INDEX nuevamente seria como hacer //un refresh aca quisiera algo como call IActionResult Index() ROMERO PREGUNTA EMILIANO return(RedirectToAction("Index")); }
internal void ChangePassword() { var client = new RestClient($"https://{this.options.Dns}"); client.AddDefaultHeader("Authorization", $"Bearer {this.token}"); this.logger.LogInformation("Change Password..."); var changePasswordRequest = new RestRequest("/v3/users?action=changepassword") { RequestFormat = DataFormat.Json, }; changePasswordRequest.AddJsonBody(JObject.FromObject(new { currentPassword = "******", newPassword = "******" }).ToString()); var changePasswordResult = client.Post(changePasswordRequest); if (changePasswordResult.StatusCode != HttpStatusCode.OK) { throw new Exception(changePasswordResult.ErrorMessage); } }
/// <summary> /// Initializes a new client with the specified credentials. /// </summary> /// <param name="accountSid">The AccountSid to authenticate with</param> /// <param name="authToken">The AuthToken to authenticate with</param> /// <param name="accountResourceSid"></param> /// <param name="apiVersion"></param> /// <param name="baseUrl"></param> public TwilioClient(string accountSid, string authToken, string accountResourceSid, string apiVersion, string baseUrl) { ApiVersion = apiVersion; BaseUrl = baseUrl; AccountSid = accountSid; AuthToken = authToken; AccountResourceSid = accountResourceSid; DateFormat = "ddd, dd MMM yyyy HH:mm:ss '+0000'"; // silverlight friendly way to get current version var assembly = Assembly.GetExecutingAssembly(); AssemblyName assemblyName = new AssemblyName(assembly.FullName); var version = assemblyName.Version; _client = new RestClient(); _client.UserAgent = "twilio-csharp/" + version + " (.NET " + Environment.Version.ToString() + ")"; _client.Authenticator = new HttpBasicAuthenticator(AccountSid, AuthToken); #if FRAMEWORK _client.AddDefaultHeader("Accept-charset", "utf-8"); #endif _client.BaseUrl = new Uri(string.Format("{0}{1}", BaseUrl, ApiVersion)); _client.Timeout = 30500; // if acting on a subaccount, use request.AddUrlSegment("AccountSid", "value") // to override for that request. _client.AddDefaultUrlSegment("AccountSid", AccountResourceSid); }
public static T Put <T>(object objectToPost, string url) where T : new() { var client = new RestClient(GlobalClass.BaseUrl + url); var request = new RestRequest(Method.PUT); request.AddHeader("Content-Type", "application/json"); string token = GlobalClass.AccessToken; if (!string.IsNullOrEmpty(GlobalClass.AccessToken)) { client.AddDefaultHeader("Authorization", "Bearer " + GlobalClass.AccessToken); } if (objectToPost != null) { request.RequestFormat = DataFormat.Json; request.AddObject(objectToPost); } var json = JsonConvert.SerializeObject(objectToPost); var response = client.Execute <T>(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return(JsonConvert.DeserializeObject <T>(response.Content)); } else { return(default(T)); } }
public static List <T> GetList <T>(string url) where T : new() { var client = new RestClient(GlobalClass.BaseUrl + url); var request = new RestRequest(Method.GET); var returnList = new List <T>(); string access = GlobalClass.AccessToken; IRestResponse <T> response; if (!string.IsNullOrEmpty(GlobalClass.AccessToken)) { client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", GlobalClass.AccessToken)); } try { response = client.Execute <T>(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { returnList = JsonConvert.DeserializeObject <List <T> >(response.Content); return(returnList); } else { Log.Debug("RestSharpCallGetList", response.Content + " status-Code " + response.StatusCode + " Token " + GlobalClass.AccessToken); return(returnList); } } catch (Exception ex) { Log.Debug("Error", ex.StackTrace); return(returnList); } }
public async Task EscapeParameterName() { var client = new RestClient("http://congress.api.sunlightfoundation.com"); string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; client.AddDefaultHeader("X-APIKEY", key); dynamic proxy = new RestSharpProxy(client); // this is the mechanism by which parameter names that are not valid c# property names can be used var parameters = new Dictionary <string, object>() { { "chamber", "senate" }, { "history.house_passage_result", "pass" } }; dynamic result = await proxy.bills.get(paramList : parameters); Assert.IsNotNull(result); Assert.IsNotNull(result.results != null); Assert.IsTrue(result.results.Count > 0); foreach (dynamic bill in result.results) { Assert.AreEqual("senate", (string)bill.chamber); Assert.AreEqual("pass", (string)bill.history.house_passage_result); } }
public TwitchTmiClient(string url = TwitchHelper.TwitchTmiUrl) { restClient = new RestClient(url); restClient.AddHandler("application/json", new DynamicJsonDeserializer()); restClient.AddHandler("text/html", new DynamicJsonDeserializer()); restClient.AddDefaultHeader("Accept", TwitchHelper.twitchAcceptHeader); }
public static List <Player> GetPlayers() { var client = new RestClient("https://api.fantasydata.net/v3/nfl/stats/JSON/PlayerSeasonStats"); var request = new RestRequest("2016REG", Method.GET); client.AddDefaultHeader(EnvironmentVariables.Key, EnvironmentVariables.Token); var response = new RestResponse(); Task.Run(async() => { response = await GetResponseContentAsync(client, request) as RestResponse; }).Wait(); JArray responseJson = JArray.Parse(response.Content); List <Player> players = new List <Player>(); foreach (var jPlayer in responseJson) { JObject player = jPlayer as JObject; var playerPosition = player["Position"].ToString(); var playerPositionCat = player["PositionCategory"].ToString(); if (playerPositionCat == "OFF" && ((playerPosition == "QB") || (playerPosition == "WR") || (playerPosition == "RB") || (playerPosition == "TE"))) { Player newPlayer = player.ToObject <Player>(); players.Add(newPlayer); } } return(players); }
public static RestClient GetClient() { var client = new RestClient(PathApi); client.AddDefaultHeader("Accept", "Application/json"); return(client); }
public static RestClient InitRestClient(Access access, string baseUrl) { var client = new RestClient { BaseUrl = new Uri(baseUrl), Timeout = 5000 }; client.UserAgent = access.UserAgent; // Set proxy if (!string.IsNullOrEmpty(access.Proxy)) { if (!string.IsNullOrEmpty(access.ProxyUsername)) // Proxy auth { ICredentials credentials = new NetworkCredential(access.ProxyUsername, access.ProxyPassword); client.Proxy = new WebProxy($"{access.Proxy}:{access.ProxyPort}", false, null, credentials); } else // Without proxy auth { client.Proxy = new WebProxy(access.Proxy, access.ProxyPort); } } client.AddDefaultHeader("Accept", "*/*"); return(client); }
public void AddHeaders(RestClient client, Dictionary <string, string> headers) { foreach (var i in headers) { client.AddDefaultHeader(i.Key, i.Value); } }
public static T Post <T>(object objectToPost, string url) where T : new() { var client = new RestClient(GlobalClass.BaseUrl + url); var request = new RestRequest(Method.POST); if (!string.IsNullOrEmpty(GlobalClass.AccessToken)) { client.AddDefaultHeader("Authorization", "Bearer " + GlobalClass.AccessToken); } if (objectToPost != null) { var json = JsonConvert.SerializeObject(objectToPost); request.AddParameter("application/json", json, ParameterType.RequestBody); } var response = client.Execute <T>(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return(JsonConvert.DeserializeObject <T>(response.Content)); } else { return(JsonConvert.DeserializeObject <T>(response.Content)); } }
static void Exec(object obj) { var client = new RestClient(_url); //这里要在获取的令牌字符串前加Bearer string tk = obj.ToString(); client.AddDefaultHeader("Authorization", tk); client.Timeout = 300000; var request = new RestRequest("/hisapi/getfeeitems", Method.GET); var radom = new Random(); var index = radom.Next(0, 36); request.AddParameter("name", arr[index]); IRestResponse response = client.Execute(request); var content = response.Content; // Console.WriteLine(DateTime.Now+" 返回状态:" +(int)response.StatusCode +"\r\n"+content); if ((int)response.StatusCode == 200) { lock (oo) { count++; } } if (count >= 1000) { Console.WriteLine($"{count} --总时间:{ (DateTime.Now - Convert.ToDateTime(Console.Title)).TotalMilliseconds}"); } }
IRestClient CreateClient(string baseUrl = null) { var client = new RestClient(baseUrl ?? connection.Url) { Authenticator = new NtlmAuthenticator() }; var deserializer = new JsonMessageDeserializer { DateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK" }; var xdeserializer = new XmlDeserializer(); client.ClearHandlers(); client.AddHandler("application/json", deserializer); client.AddHandler("text/json", deserializer); client.AddHandler("text/x-json", deserializer); client.AddHandler("text/javascript", deserializer); client.AddHandler("application/xml", xdeserializer); client.AddHandler("text/xml", xdeserializer); client.AddHandler("*", xdeserializer); client.AddDefaultHeader("Accept-Encoding", "gzip,deflate"); return(client); }
public Nuan(HouseDapper houseDapper, ConfigDapper configDapper, ElasticService elastic, RedisTool redisTool) : base(houseDapper, configDapper, elastic, redisTool) { _restClient = new RestClient("https://nuan.io"); _restClient.AddDefaultHeader("user-agent", "Mozilla/5.0 (Linux; Android 5.1; vivo V3M A Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 MicroMessenger/7.0.3.1400(0x2700033C) Process/appbrand0 NetType/WIFI Language/zh_CN"); this.Source = SourceEnum.Nuan; }
public ApiClient(string baseUrl) { BaseUrl = baseUrl; RestClient = new RestClient(baseUrl); RestClient.UseNewtonsoftJson(); RestClient.AddDefaultHeader("Content-Type", "application/json; charset=utf-8"); }
public async Task <PlayResponse> ChamarSpotifyApi(PlayRequest playRequest) { // Gera token de acesso string token = await GerarTokenAcesso(); // Cria objeto de conexao com spotify-api RestClient api = new RestClient(); api.AddDefaultHeader("Authorization", "Bearer " + token); // Cria body-request para enviar para spotify-api RestRequest request = new RestRequest(URL_SPOTIFY_PLAY, Method.PUT); request.AddJsonBody(new SpotifyPlayRequest(playRequest.MusicaURI)); // Chama spotify-api verbo PUT IRestResponse spotifyResponse = await api.ExecuteAsync(request); // Se api expirou, reseta token if (spotifyResponse.StatusCode == HttpStatusCode.Unauthorized) { TOKEN = string.Empty; } // Cria objeto reponse PlayResponse response = new PlayResponse((int)spotifyResponse.StatusCode, spotifyResponse.Content); return(response); }
private async Task <string> GetDataAsync(string restOfUrl, bool hMacSha256Enabled, RequestMethod method, string args = null) { string url = _mainUrl + restOfUrl; if (args != null) { if (hMacSha256Enabled) { var signature = args.CreateHMAC256Signature(_secretKey); url += $"?{args}&signature={signature}"; } else { url += $"?{args}"; } } var client = new RestClient(url); client.AddDefaultHeader("X-MBX-APIKEY", _apiKey); IRestResponse response; if (method == RequestMethod.Get) { response = await client.ExecuteAsync(new RestRequest()); } else if (method == RequestMethod.Post) { response = await client.ExecutePostAsync(new RestRequest()); } else { response = await client.ExecuteAsync(new RestRequest()); } return(response.Content); }
protected void subButton_Click(object sender, EventArgs e) { lblmsg.Text = ""; if (!String.IsNullOrEmpty(this.txtEmail.Text)) { bool isEmail = Regex.IsMatch(this.txtEmail.Text, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase); if (isEmail) { RestClient _client; SitePreference sitePreference = CSFactory.GetCacheSitePref(); _client = new RestClient(sitePreference.GetAttributeValue <string>("Url_Klaviyo", "")); _client.AddDefaultHeader("Content-Type", "application/json"); var request = new RestRequest("api/v1/list/" + sitePreference.GetAttributeValue <string>("Key_EmailPopSignups", "") + "/members?api_key=" + sitePreference.GetAttributeValue <string>("APIKey_Klaviyo", "") + "&email=" + this.txtEmail.Text, Method.POST); request.AddParameter("email", this.txtEmail.Text); /* If this paramter is set to true we dont get the person id and * email is not added into Klaviyo list until the person confirms his subscription */ request.AddParameter("confirm_optin", false); IRestResponse response = _client.Execute(request); dynamic obj = JsonConvert.DeserializeObject(response.Content); if (response.StatusCode == HttpStatusCode.OK && obj != null) { if (obj["already_member"].Value == false) { lblmsg.Text = "Thank you for signing up!"; lblmsg.ForeColor = System.Drawing.ColorTranslator.FromHtml("#039029"); SaveContact(this.txtEmail.Text); this.txtEmail.Text = ""; lblmsg.Visible = true; } else { this.txtEmail.Text = ""; lblmsg.Visible = true; lblmsg.ForeColor = System.Drawing.Color.Red; lblmsg.Text = "Email address entered is already registered"; } } } else { lblmsg.Visible = true; lblmsg.ForeColor = System.Drawing.Color.Red; lblmsg.Text = "Please enter a valid email address"; } } else { lblmsg.Visible = true; lblmsg.Text = "Please enter an email address"; lblmsg.ForeColor = System.Drawing.Color.Red; } }
private void LogInButton_Click(object sender, RoutedEventArgs e) { RestRequest request = new RestRequest("/Token", Method.POST); request.AddParameter("grant_type", "password"); request.AddParameter("userName", mailTextBox.Text); request.AddParameter("password", PasswordBox.Password); var response = _client.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { string accessToken = JObject.Parse(response.Content)["access_token"].ToString(); _client.AddDefaultHeader("Authorization", $"Bearer { accessToken }"); MainWindow main = new MainWindow(_client); main.Show(); this.Close(); } else { mailTextBox.Text = ""; PasswordBox.Password = ""; BadSignIn.Content = "Forkert email/password kombination. Prøv igen."; BadSignIn.Visibility = Visibility.Visible; } }
public ActionResult AddTopic(HttpPostedFileBase photo) { try { var sujet = Request.Form["subject"]; var contenu = Request.Form["message"]; var soucat = Request.Form["subject1"]; var x = Ss.getByName(soucat); var top = new topic(); top.contenu = (sujet); top.sujet = (contenu); var restClient = new RestClient("http://localhost:18080/insurance-web/api/"); restClient.AddDefaultHeader("accept", "*/*"); var request = new RestRequest("Topic?id=" + x[0].idSousCategory, Method.POST); request.AddJsonBody(new { sujet = sujet, contenu = contenu }); var response = restClient.Execute(request); return(RedirectToAction("First")); } catch (Exception ex) { ViewBag.Message = "ERROR:" + ex.Message.ToString(); return(RedirectToAction("AddTopic")); } }
public DigitalOceanClient(string token) { var client = new RestClient(DigitalOceanApiUrl) { UserAgent = "digitalocean-api-dotnet" }; client.AddDefaultHeader("Authorization", $"Bearer {token}"); _connection = new Connection(client); Actions = new ActionsClient(_connection); DomainRecords = new DomainRecordsClient(_connection); Domains = new DomainsClient(_connection); DropletActions = new DropletActionsClient(_connection); Droplets = new DropletsClient(_connection); FloatingIps = new FloatingIpsClient(_connection); FloatingIpActions = new FloatingIpActionsClient(_connection); ImageActions = new ImageActionsClient(_connection); Images = new ImagesClient(_connection); Keys = new KeysClient(_connection); Regions = new RegionsClient(_connection); Sizes = new SizesClient(_connection); Snapshots = new SnapshotsClient(_connection); Tags = new TagsClient(_connection); Volumes = new VolumesClient(_connection); }
public GameServerClient() { _restClient = new RestClient(ServerUrl); _restClient.AddDefaultHeader("Accept", "application/xml"); _restClient.AddHandler("application/xml", new DataContractDeserializer(_knownTypes)); _knownTypes = GetKnownTypes(); }
public string TwitterAuthenticate(string user, string pass) { client.CookieContainer = _cookieJar; //RestClient client = new RestClient("https://twitter.com"); IRestRequest request = new RestRequest("https://twitter.com/", Method.GET); client.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0"; client.AddDefaultHeader("Accept", "*/*"); //request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method //request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource // easily add HTTP Headers //request.AddHeader("header", "value"); // add files to upload (works with compatible verbs) // execute the request IRestResponse response = client.Execute(request); var content = response.Content; Match m = Regex.Match(content, @"name=""authenticity_token""\s*value=""(.*?)"">"); string authenticity_token = m.Groups[1].Value; request = new RestRequest("https://twitter.com/sessions", Method.POST); request.AddParameter("session[username_or_email]", user); request.AddParameter("session[password]", pass); request.AddParameter("return_to_ssl", "true"); request.AddParameter("scribe_log", ""); request.AddParameter("redirect_after_login", "/"); request.AddParameter("authenticity_token", authenticity_token); response = client.Execute(request); content = response.Content; return content; }
//------------------------------------------------------------------------------------------------------- //Actual filing public dynamic Efile(string id, string payload, List <string> filepaths) { try { var client = new RestClient(BASE_URL + AppConstants.EFILE_API); client.ConfigureWebRequest((r) => { r.ServicePoint.Expect100Continue = false; r.KeepAlive = true; }); client.Timeout = 60000; client.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; client.AddDefaultHeader("authtoken", authtoken); var request = new RestRequest(Method.POST); request.AddParameter("meta_data", payload); request.AddParameter("strict", "false"); foreach (var filepath in filepaths) { request.AddFile("file", filepath); } request.AlwaysMultipartFormData = true; IRestResponse response = client.Execute(request); dynamic json = SimpleJson.DeserializeObject(response.Content); if (!response.IsSuccessful) { throw new Exception(json["message"]); } json["id"] = id; return(json); } catch (Exception) { throw; } }
public bool getLoginTokens(string login, string password) { Models.AppData appdata = App.Database.GetAppDataAsync().Result; /*if (appdata != null) * { * deviceid = appdata.DeviceID; * }*/ var client = new RestClient("https://www.kresgefor98.com/rest/CFCandidate/"); client.AddDefaultHeader("Content-type", "application/json"); var request = new RestRequest("token", Method.POST); var requestbody = new { login = login, password = password }; request.RequestFormat = DataFormat.Json; request.AddJsonBody(requestbody); var response = client.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { return(false); } var newappdata = JsonConvert.DeserializeObject <Models.AppData>(response.Content); App.Database.UpdateAppData(newappdata); access_token = newappdata.Access_Token; expires_in = newappdata.Expires_In; return(true); }