public RestSharp.IRestResponse SendRequest(int maxRetry = 10) { var client = new RestSharp.RestClient(); RestSharp.IRestResponse response = client.Execute(Request); return(response); }
private RestResponse BuildRestResponse(RestSharp.IRestResponse restSharpResponse) { var restResponse = new RestResponse(); restResponse.Content = restSharpResponse.Content; restResponse.ContentEncoding = restSharpResponse.ContentEncoding; restResponse.ContentLength = restSharpResponse.ContentLength; restResponse.ContentType = restSharpResponse.ContentType; //TODO: solve this mapping //toReturn.Cookies = restSharpResponse.Cookies; restResponse.ErrorException = restSharpResponse.ErrorException; restResponse.ErrorMessage = restSharpResponse.ErrorMessage; //TODO: solve this mapping //toReturn.Headers = restSharpResponse.Headers, restResponse.RawBytes = restSharpResponse.RawBytes; //TODO: solve this mapping //toReturn.Request = restRequest; restResponse.ResponseStatus = (ResponseStatus)Enum.Parse(typeof(ResponseStatus), restSharpResponse.ResponseStatus.ToString()); restResponse.ResponseUri = restSharpResponse.ResponseUri; restResponse.Server = restSharpResponse.Server; restResponse.StatusCode = (ResponseHttpStatusCode)Enum.Parse(typeof(ResponseHttpStatusCode), restSharpResponse.StatusCode.ToString()); restResponse.StatusDescription = restSharpResponse.StatusDescription; return(restResponse); }
public string GetKB(string question) { string qnamakerUriBase = $"https://{ConfigurationManager.AppSettings["QnAApiHostName"]}/qnamaker/v1.0"; string apiApppId = ConfigurationManager.AppSettings["QnAKnowledgebaseId"]; string apiKey = ConfigurationManager.AppSettings["QnASubscriptionKey"]; string body = $"{{\"question\" : \"{question}\"}}"; qnamakerUriBase += $"/knowledgebases/{apiApppId}/generateAnswer"; RestSharp.RestClient client = new RestSharp.RestClient(qnamakerUriBase) { Encoding = System.Text.Encoding.UTF8, }; RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST); // Add Header request.AddHeader("Content-Type", "application/json"); request.AddHeader("Ocp-Apim-Subscription-Key", apiKey); request.AddHeader("cache-control", "no-cache"); // Add Body request.AddParameter("undefined", body, RestSharp.ParameterType.RequestBody); // Send the Post Request RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
private void Button_Click_1(object sender, RoutedEventArgs e) { var name = (String)username.Text; var passw = (String)password.Password; var client = new RestSharp.RestClient("http://" + Config.WebHostIP + ":" + Config.WebHostPort + "/omlate"); var request = new RestSharp.RestRequest("/Instructor/validateUsernamePassword", RestSharp.Method.POST); request.AddParameter("username", name); request.AddParameter("password", passw); RestSharp.IRestResponse response = client.Execute(request); var content = response.Content; bool cont = Convert.ToBoolean(content); if (cont) { Properties.Settings.Default["username"] = name; this.Hide(); if (swindow == null) { swindow = new StartLectureWindow(); } swindow.ShowDialog(); } else { label.Content = "*Invalid Username or Password!"; Properties.Settings.Default["username"] = "******"; } Properties.Settings.Default.Save(); //Toolbar toolbar = new Toolbar(); //toolbar.Show(); //this.Close(); }
public T Deserialize <T>(RestSharp.IRestResponse response) { using (var textStream = new StringReader(response.Content)) { var reader = new JsonTextReader(textStream); return(_serializer.Deserialize <T>(reader)); } }
private void DownloadFills() { // Perform REST request/response to download fill data, specifying our cached minimum timestamp as a starting point. // On a successful response the timestamp will be updated so we run no risk of downloading duplicate fills. List <TT_Fill> fills = new List <TT_Fill>(); do { var min_param = new RestSharp.Parameter("minTimestamp", TT_Info.ToRestTimestamp(m_minTimeStamp).ToString(), RestSharp.ParameterType.QueryString); RestSharp.IRestResponse result = RestManager.GetRequest("ledger", "fills", min_param); if (result.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception("Request for fills unsuccessful. Status:" + result.StatusCode.ToString() + "Error Message: " + result.ErrorMessage); } JObject json_data = JObject.Parse(result.Content); foreach (var fill in json_data["fills"]) { fills.Add(new TT_Fill(fill)); } fills.Sort((f1, f2) => f1.UtcTimeStamp.CompareTo(f2.UtcTimeStamp)); RaiseFillDownloadEvent(fills); if (fills.Count > 0 && m_running) { m_minTimeStamp = new DateTime(fills[fills.Count - 1].UtcTimeStamp.Ticks + 1); } }while (fills.Count == TT_Info.MAX_RESPONSE_FILLS); }
public IActionResult GetClientComputerName(string ip) { try { Config config = ConfigJSON.Read(); string url = "http://" + ip + ":" + config.ClientPort + "/POSClient/GetComputerName"; var client = new RestSharp.RestClient(url); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("Access-Control-Allow-Origin", "*"); RestSharp.IRestResponse response = client.Execute(request); string pcName = response.Content.Replace("\"", ""); int terminalId = 0; //check if terminal is assigned TerminalMapping terminalMapping = _context.TerminalMapping.FirstOrDefault(x => x.PCName == pcName); Terminal terminal = new Terminal(); if (terminalMapping != null) { terminal = _context.Terminal.FirstOrDefault(x => x.Id == terminalMapping.TerminalId); } return(Ok(new { pcName = pcName, terminalId = terminalMapping.TerminalId.ToString(), terminalName = terminal?.Name })); } catch (Exception ex) { return(StatusCode(500)); } }
public T Deserialize <T>(RestSharp.IRestResponse response) { if (response.Content == null) { return(default(T)); } // 2012-07-26 - attempt to handle some of the bad json content, eg Similar Movies for id 80271 containing null values // amongst the other objects in the results array // eg ...."vote_average":0.0,"vote_count":0},null,null,{"backdrop_path":null,"id":73736,"original_title":... // ^^^^ ^^^^ // Causes "Object reference not set to an instance of an object" exception during deserialization while (response.Content.IndexOf("},null,") != -1) { response.Content = response.Content.Replace("},null,", "},"); } while (response.Content.IndexOf("[null,") != -1) { response.Content = response.Content.Replace("[null,", "["); } var deserializer = new JsonDeserializer(); var data = deserializer.Deserialize <T>(response); return(data); }
private void button1_Click(object sender, EventArgs e) { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("https://www.skyscanner.com"); driver.FindElement(By.XPath("//*[@HeaderTab_HeaderTab__text___djus HeaderTab_HeaderTab__text--large__3GG4Z]")).Click(); driver.FindElement(By.Id("destination-autosuggest")).SendKeys("Muğla"); driver.FindElement(By.Id("guests - rooms")).SendKeys("room"); var client = new RestSharp.RestClient("https://hotels4.p.rapidapi.com/locations/search?locale=en_US&query=new%20york"); var request = new RestSharp.RestRequest(RestSharp.Method.GET); request.AddHeader("x-rapidapi-host", "hotels4.p.rapidapi.com"); request.AddHeader("x-rapidapi-key", "6bcc2d1861mshfa70f85a843bbe8p142731jsndc2ac6412dab"); RestSharp.IRestResponse response = client.Execute(request); /* * var client = new RestClient("https://hotels4.p.rapidapi.com/locations/search?locale=en_US&query=new%20york"); * var request = new RestRequest(Method.GET); * request.AddHeader("x-rapidapi-host", "hotels4.p.rapidapi.com"); * request.AddHeader("x-rapidapi-key", "6bcc2d1861mshfa70f85a843bbe8p142731jsndc2ac6412dab"); * IRestResponse response = client.Execute(request); */ }
public static string UpdateCustomer() { var client = new RestSharp.RestClient("https://lab.cardnet.com.do/servicios/tokens/v1/api/Customer/1047/update") { Timeout = -1 }; var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic PrivateAccountKey"); request.AddParameter("application/json", "{" + "\"CustomerID\": 1047,\n" + "\"Email\": \"[email protected]\",\n" + "\"ShippingAddress\": \"Calle Max Henriquez Ureña No. 6\",\n" + "\"BillingAddress\": \"Calle 1 No 10, Piantini\",\n" + "\"FirstName\": \"Emmanuel\",\n" + "\"LastName\": \"De los Santos\",\n" + "\"DocumentTypeId\": 2,\n" + "\"DocNumber\": \"00114918123\",\n" + "\"PhoneNumber\": \"8096043111\" ,\n" + "\"Enable\": true }" , RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
/// <summary> /// Ejecuta la llamada al servicio REST con RestSharp /// </summary> /// <typeparam name="T">Tipo de dato del objeto de retorno</typeparam> /// <param name="uri">url del endpoint del servicio rest</param> /// <param name="httpMethod">Método HTTP</param> /// <param name="objJsonBody">Objeto request body</param> /// <returns>Interface IRestResponse<T></returns> public static RestSharp.IRestResponse<T> Execute<T>(string uri, RestSharp.Method httpMethod, object objJsonBody = null, string authorizationHeader = null) where T : new() { var client = new RestSharp.RestClient(uri); var request = new RestSharp.RestRequest(httpMethod); request.AddHeader("cache-control", "no-cache"); request.AddHeader("Content-Type", "application/json"); if (!string.IsNullOrEmpty(authorizationHeader)) { request.AddHeader("Authorization", authorizationHeader); } if (objJsonBody != null) request.AddParameter("application/json", objJsonBody, RestSharp.ParameterType.RequestBody); //request.AddJsonBody(objJsonBody); System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; RestSharp.IRestResponse<T> response = null; for (int i = 0; i < 2; i++) { response = client.Execute<T>(request); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) break; else if (response.StatusCode == HttpStatusCode.RequestTimeout || (int)response.StatusCode > 500) Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["timer_web_api"])); } return response; }
//public string PrivateAccountKey ="PrivateAccountKey"; public static string PostPurchase() { var client = new RestSharp.RestClient("https://lab.cardnet.com.do/servicios/tokens/v1/api/Purchase") { Timeout = -1 }; var request = new RestSharp.RestRequest(RestSharp.Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", "Basic PrivateAccountKey"); request.AddParameter("application/json", "{" + "\"TrxToken\": \"CT__6NBt_OO5gfCg7RUCF_xdtRuaohj8YOAjLqkyXVed23g_\",\n" + "\"Order\": \"000001\",\n" + "\"Amount\": 13000,\n" + "\"Tip\": 000,\n" + "\"Currency\": \"DOP\",\n" + "\"Capture\": true,\n" + "\"CustomerIP\": \"100.0.0.2\",\n" + "\"DataDo\": { \"Tax\": 000,\n \"Invoice\": \"000001\",\n }" + "}", RestSharp.ParameterType.RequestBody); RestSharp.IRestResponse response = client.Execute(request); return(response.Content); }
public RestSharp.IRestResponse CreateQuestion(CreateQuestionDTO createQuestionDTO) { JsonObject json = new JsonObject(); json.Add("professionCode", createQuestionDTO.ProfessionCode); json.Add("imageUrl", createQuestionDTO.ImageUrl); json.Add("correctAnswerIndex", createQuestionDTO.CorrectAnswerIndex); json.Add("content", createQuestionDTO.Question); JsonArray answers = new JsonArray(); foreach (var answer in createQuestionDTO.Answers) { answers.Add(answer); } json.Add("answers", answers); RestSharp.RestRequest request = new RestSharp.RestRequest("question", RestSharp.Method.POST); request.AddJsonBody(json); RestSharp.IRestResponse response = Execute(request); return(response); }
private static void Done(RestSharp.IRestResponse response, RestSharp.RestRequestAsyncHandle handle) { if (response.ErrorException != null && mExceptionLog != null) { mExceptionLog(response.ErrorMessage, response.ErrorException); } }
public SDK.Http.IHttpResponse ToHttpResponse(RestSharp.IRestResponse response) { bool transportError = false; var responseMessages = new List <string>(); transportError = response.ResponseStatus == RestSharp.ResponseStatus.TimedOut || response.ResponseStatus == RestSharp.ResponseStatus.Aborted; if (response.ErrorException != null) { responseMessages.Add(response.ErrorException.Message); } else if (!string.IsNullOrEmpty(response.ErrorMessage)) { responseMessages.Add(response.ErrorMessage); } if (!string.IsNullOrEmpty(response.StatusDescription)) { responseMessages.Add(response.StatusDescription); } var headers = this.ToHttpHeaders(response.Headers); return(new Impl.Http.DefaultHttpResponse( (int)response.StatusCode, string.Join(Environment.NewLine, responseMessages), headers, response.Content, response.ContentType, transportError)); }
public void Update(string city) { try{ System.Text.StringBuilder str = new System.Text.StringBuilder(city); str.Remove(0, 13); city = str.ToString(); } catch (Exception) { //todo replace city with user's or use default } Console.WriteLine(city); foreach (var i in cityList) { if (city.Equals(i.name) | city.Equals(i.name_lowecase)) { id = i.id; } } var client = new RestSharp.RestClient("http://api.openweathermap.org/data/2.5"); var request = new RestSharp.RestRequest("weather?id=" + id + "&APPID=cbe768adbe16ad6ce8c15294944172ac"); RestSharp.IRestResponse responce = client.Execute(request); var content = responce.Content; //Console.WriteLine(content); Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JToken.Parse(content); dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(content); var main = obj.main; value = main.temp - 273.15; var weather = obj.weather; description = weather[0].description; location = obj.name; Console.WriteLine("weather data updated"); }
public RestSharp.IRestResponse GetAllQualifications() { RestSharp.RestRequest request = new RestSharp.RestRequest("qualifications", RestSharp.Method.GET); RestSharp.IRestResponse response = Execute(request); return(response); }
public RestSharp.IRestResponse GetAllClasses() { RestSharp.RestRequest request = new RestSharp.RestRequest("/admin/classes", RestSharp.Method.GET); RestSharp.IRestResponse response = Execute(request); return(response); }
public RestSharp.IRestResponse GetAllClassUsers(string className) { RestSharp.RestRequest request = new RestSharp.RestRequest("/admin/" + className + "/users", RestSharp.Method.GET); RestSharp.IRestResponse response = Execute(request); return(response); }
public RestSharp.IRestResponse GetActiveExam() { RestSharp.RestRequest request = new RestSharp.RestRequest("exams", RestSharp.Method.GET); RestSharp.IRestResponse response = Execute(request); return(response); }
public void GivenWhenICallTheGETEndpointWith(string carName) { //Creating an instance of the class Test Test test = new Test(); //Reading the responsf from test method into a Irest response restResponse = test.TestMethod1(carName); }
public RestSharp.IRestResponse GetUserExams() { RestSharp.RestRequest request = new RestSharp.RestRequest("/user/my/exam", RestSharp.Method.GET); RestSharp.IRestResponse response = Execute(request); return(response); }
public T Deserialize <T>(RestSharp.IRestResponse response) { var content = response.Content; using var stringReader = new StringReader(content); using var jsonTextReader = new JsonTextReader(stringReader); return(serializer.Deserialize <T>(jsonTextReader)); }
public void ThenVerifyFollowingResponseValues(Table table) { // Verify the reponse value by verifyGivenNodeValue function ServiceDetailsForReport = ""; response = RestApiHelper.getResponse(); jsonObj = JObject.Parse(response.Content); RestApiHelper.verifyGivenNodeValue(table, jsonObj); }
private static void elaborateQueue(Dictionary <string, List <string> > listFile, string token, bool pretty) { int totalfile = listFile.Sum(x => x.Value.Count); int partialOfTotal = 0; foreach (KeyValuePair <string, List <string> > c in listFile) { int progress = 0; foreach (string item in c.Value) { log.Info($"Processing file {++progress} of {c.Value.Count} in collection: {c.Key}"); string contentFile = File.ReadAllText(item); log.Request(contentFile); RestSharp.IRestResponse responseRawCMS = RawCmsHelper.CreateElement(new CreateRequest { Collection = c.Key, Data = contentFile, Token = token }); log.Debug($"RawCMS response code: {responseRawCMS.StatusCode}"); if (!responseRawCMS.IsSuccessful) { //log.Error($"Error occurred: \n{responseRawCMS.Content}"); log.Error($"Error: {responseRawCMS.ErrorMessage}"); } else { log.Response(responseRawCMS.Content); } //switch (responseRawCMS.ResponseStatus) //{ // case RestSharp.ResponseStatus.Completed: // log.Response(responseRawCMS.Content); // break; // case RestSharp.ResponseStatus.None: // case RestSharp.ResponseStatus.Error: // case RestSharp.ResponseStatus.TimedOut: // case RestSharp.ResponseStatus.Aborted: // default: // log.Error($"Error response: {responseRawCMS.ErrorMessage}"); // break; //} log.Info($"File processed\n\tCollection progress: {progress} of {c.Value.Count}\n\tTotal progress: {++partialOfTotal} of {totalfile}\n\tFile: {item}\n\tCollection: {c.Key}"); } } }
public DipendenteRest GetDipendenteRest(string matricola) { DipendenteRest dr = new DipendenteRest(); try { var client = new RestSharp.RestClient("http://bell.ice.it:5000"); var req = new RestSharp.RestRequest("api/dipendente", RestSharp.Method.GET); req.RequestFormat = RestSharp.DataFormat.Json; req.AddParameter("matricola", matricola); RestSharp.IRestResponse <RetDipendenteJson> resp = client.Execute <RetDipendenteJson>(req); if (resp.StatusCode == HttpStatusCode.BadRequest || resp.StatusCode == HttpStatusCode.InternalServerError || resp.StatusCode == HttpStatusCode.NotFound) { return(dr); } RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer(); RetDipendenteJson retDip = deserial.Deserialize <RetDipendenteJson>(resp); if (resp.StatusCode == System.Net.HttpStatusCode.OK) { if (retDip.success == true) { if (retDip.items != null) { using (dtAccount dta = new dtAccount()) { dr.matricola = retDip.items.matricola; dr.cognome = retDip.items.cognome; dr.nome = retDip.items.nome; dr.cdf = retDip.items.cdf; dr.dataAssunzione = retDip.items.dataAssunzione; dr.dataCessazione = retDip.items.dataCessazione; dr.indirizzo = retDip.items.indirizzo; dr.cap = retDip.items.cap; dr.citta = retDip.items.citta; dr.provincia = retDip.items.provincia; dr.livello = retDip.items.livello; dr.cdc = retDip.items.cdc; dr.email = retDip.items.email; dr.disabilitato = retDip.items.disabilitato; dr.password = retDip.items.password; } } } } return(dr); } catch (Exception ex) { throw ex; } }
public RestSharp.IRestResponse SubmitExam(SubmitExamDTO submitExamDTO) { RestSharp.RestRequest request = new RestSharp.RestRequest("exam", RestSharp.Method.PUT); request.JsonSerializer = new NewtonsoftJsonSerializer(); request.AddJsonBody(submitExamDTO); RestSharp.IRestResponse response = Execute(request); return(response); }
public RestSharp.IRestResponse LoginUser(LoginUserDTO loginUserDTO) { RestSharp.RestRequest request = new RestSharp.RestRequest("login", RestSharp.Method.POST); request.AddParameter("username", loginUserDTO.Username); request.AddParameter("password", loginUserDTO.Password); RestSharp.IRestResponse response = Execute(request); return(response); }
public RestSharp.IRestResponse GetExamById(string id) { RestSharp.RestRequest request = new RestSharp.RestRequest("/exam/{id}", RestSharp.Method.GET); request.JsonSerializer = new NewtonsoftJsonSerializer(); request.AddParameter("id", id, RestSharp.ParameterType.UrlSegment); RestSharp.IRestResponse response = Execute(request); return(response); }
private Exception CreateException(RestSharp.IRestResponse response) { var ex = new Exception(); ex.Data.Add("StatusCode", response.StatusCode); ex.Data.Add("Content", response.Content); ex.Data.Add("ContentType", response.ContentType); return(ex); }