Example #1
0
        public bool PushConsumeMessage(string token, dynamic jsonObject)
        {
            var client  = new RestSharp.RestClient(URL_CUSTOM_SEND);
            var request = new RestSharp.RestRequest($"cgi-bin/message/custom/send?access_token={token}", RestSharp.Method.POST);

            request.AddJsonBody(jsonObject);
            var response = client.Execute(request);

            if (response.IsSuccessful)
            {
                try
                {
                    var model = JsonConvert.DeserializeObject <ConsumeMessageResponse>(response.Content);
                    if (model.errcode == 0)
                    {
                        return(true);
                    }
                    Logger.Info(
                        $"PushConsumeMessage Faild errorcode = {model.errcode} errormsg={model.errmsg} body={JsonConvert.SerializeObject(jsonObject)}");
                    return(false);
                }
                catch (Exception e)
                {
                    Logger.Error("PushConsumeMessage Error", e);
                }
            }
            return(false);
        }
Example #2
0
        public string Post(string url, string payload, string time, bool requestId)
        {
            var client  = new RestSharp.RestClient(_apiDomain);
            var request = new RestSharp.RestRequest(url);

            request.AddHeader("Accept", "application/json");
            request.AddHeader("Content-type", "application/json");

            string nonce  = Guid.NewGuid().ToString();
            string digest = HashBySegments(_apiSecret, _apiKey, time, nonce, _organizationID, "POST", GetPath(url), GetQuery(url), payload);

            if (payload != null)
            {
                request.AddJsonBody(payload);
            }

            request.AddHeader("X-Time", time);
            request.AddHeader("X-Nonce", nonce);
            request.AddHeader("X-Auth", _apiKey + ":" + digest);
            request.AddHeader("X-Organization-Id", _organizationID);

            if (requestId)
            {
                request.AddHeader("X-Request-Id", Guid.NewGuid().ToString());
            }

            var response = client.Execute(request, RestSharp.Method.POST);
            var content  = response.Content;

            return(content);
        }
Example #3
0
        public async Task <TrustedPublisher> GetTrustedPublisher(string url)
        {
            client = new RestSharp.RestClient(configuration.GetValue <string>("ApimBaseUrl"));
            RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/we-trustedpublisher-func/GetTrustedPublisher", RestSharp.Method.POST);

            restRequest.AddHeader("Ocp-Apim-Subscription-Key", configuration.GetValue <string>("ApimKey"));
            restRequest.AddHeader("Content-Type", "application/json");

            TrustedPublisherRequest publisherRequest = new TrustedPublisherRequest()
            {
                Url = url
            };

            restRequest.AddJsonBody(publisherRequest);

            try
            {
                var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);

                return(JsonConvert.DeserializeObject <TrustedPublisher>(response.Content));
            }
            catch (Exception)
            {
                return(new TrustedPublisher()
                {
                    Reason = "Konnte leider nicht validiert werden"
                });
            }
        }
        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);
        }
        public static async Task <string> GetTwitter([ActivityTrigger] string request,
                                                     ILogger log)
        {
            client = new RestSharp.RestClient("https://we-factsearch-fa.azurewebsites.net");

            RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/api/SearchTwitter", RestSharp.Method.POST);

            restRequest.AddHeader("Content-Type", "application/json");
            Model.RootObject requestData = JsonConvert.DeserializeObject <Model.RootObject>(request);

            string query = string.Empty;

            foreach (var item in requestData.documents[0].keyPhrases)
            {
                query += item + " ";
            }

            Model.SearchQuery searchQuery = new Model.SearchQuery()
            {
                query = query
            };

            restRequest.AddJsonBody(searchQuery);

            var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);

            return(response.Content);
        }
Example #6
0
        public async Task <T> Post <T, K>(string url, K objecttosend)
        {
            try
            {
                Debugger.WriteLine("RestSharp: " + url);
                var client     = new RestSharp.RestClient(url);
                var request    = new RestSharp.RestRequest(RestSharp.Method.POST);
                var jsonstring = objecttosend.SerializeObject();
                request.AddJsonBody(jsonstring);
                request.RequestFormat = RestSharp.DataFormat.Json;
                var response = await client.ExecuteTaskAsync(request);

                if (response != null)
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        Debugger.WriteLine("RestSharp: " + response.Content);
                        return(response.Content.DeserializeObject <T>());
                    }
                }
            }
            catch (Exception ex)
            {
                Debugger.WriteLine("RestSharp: " + ex.StackTrace);
            }
            return(default(T));
        }
Example #7
0
        public string post(string url, string payload, bool requestId)
        {
            string time    = this.srvrTime();
            var    client  = new RestSharp.RestClient(this.urlRoot);
            var    request = new RestSharp.RestRequest(url);

            request.AddHeader("Accept", "application/json");
            request.AddHeader("Content-type", "application/json");

            string nonce  = Guid.NewGuid().ToString();
            string digest = Api.HashBySegments(this.apiSecret, this.apiKey, time, nonce, this.orgId, "POST", getPath(url), getQuery(url), payload);

            if (payload != null)
            {
                request.AddJsonBody(payload);
            }

            request.AddHeader("X-Time", time);
            request.AddHeader("X-Nonce", nonce);
            request.AddHeader("X-Auth", this.apiKey + ":" + digest);
            request.AddHeader("X-Organization-Id", this.orgId);

            if (requestId)
            {
                request.AddHeader("X-Request-Id", Guid.NewGuid().ToString());
            }

            var response = client.Execute(request, RestSharp.Method.POST);
            //Console.Out.WriteLine("res: [" + response.Content + "]");
            var content = response.Content;

            return(content);
        }
Example #8
0
        public async Task <List <Models.SearchResponse> > GetFakeNewsDb(string message)
        {
            try
            {
                client = new RestSharp.RestClient(configuration.GetValue <string>("ApimBaseUrl"));

                RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/we-factsearch-fa/Search", RestSharp.Method.POST);

                restRequest.AddHeader("Ocp-Apim-Subscription-Key", configuration.GetValue <string>("ApimKey"));
                restRequest.AddHeader("Content-Type", "application/json");

                Models.Request requestObject = new Models.Request
                {
                    text = message
                };

                restRequest.AddJsonBody(requestObject);

                var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);

                return(JsonConvert.DeserializeObject <List <Models.SearchResponse> >(response.Content));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #9
0
        public IResponse Execute(IRequest request, HttpStatusCode andExpect)
        {
            var rc = new RestSharp.RestClient(_testSettings.BaseUrl);
            var rr = new RestSharp.RestRequest(request.RelativeUrl, request.Method);

            if (request.Body != null)
            {
                rr.AddJsonBody(request.Body);
            }

            _logger.Information("{Event} {HttpMethod} {BaseUrl}{RelativeUrl} {@request}", "TestStartHttpRequest", request.Method, _testSettings.BaseUrl, request.RelativeUrl, request);
            var response = rc.Execute(rr);

            _logger.Write(response.StatusCode == andExpect ?
                          Serilog.Events.LogEventLevel.Information :
                          Serilog.Events.LogEventLevel.Error,
                          "{Event} {HttpMethod} {BaseUrl}{RelativeUrl} {StatusCode} {ExpectedStatusCode}", "TestEndHttpRequest", request.Method, _testSettings.BaseUrl, request.RelativeUrl, response.StatusCode, andExpect);

            if (response.StatusCode != andExpect)
            {
                throw new WebException($"The call to {request.Method} {_testSettings.BaseUrl}{request.RelativeUrl} was expected to return {andExpect} but returned {response.StatusCode}");
            }

            return(new Response(response));
        }
Example #10
0
        public void UpdateUserTest()
        {
            RestSharp.RestClient  client  = new RestSharp.RestClient("http://localhost:50235/api/user");
            RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.GET);
            List <User>           users   = new List <User>();

            users = client.Execute <List <User> >(request).Data;
            if (users == null || users.Count == 0)
            {
                Assert.Fail();
            }
            var user = users.FirstOrDefault();

            var updateUser = user;

            updateUser.Phone = "2500";
            client           = new RestSharp.RestClient("http://localhost:50235/api/user/");
            request          = new RestSharp.RestRequest(RestSharp.Method.PUT);
            request.AddJsonBody(updateUser);
            var responesUpdate = client.Execute <bool>(request);

            Assert.IsTrue(responesUpdate.Data);
            client  = new RestSharp.RestClient("http://localhost:50235/api/user");
            request = new RestSharp.RestRequest(RestSharp.Method.GET);
            users   = new List <User>();
            users   = client.Execute <List <User> >(request).Data;
            Assert.IsTrue(users.FirstOrDefault().Phone.Equals("2500"));
        }
Example #11
0
        public async Task <ScraperResponse> GetWebScraperResult(string url)
        {
            client = new RestSharp.RestClient(configuration.GetValue <string>("ApimBaseUrl"));
            RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/we-webscraper-func/WebScraperFunc", RestSharp.Method.POST);

            restRequest.AddHeader("Ocp-Apim-Subscription-Key", configuration.GetValue <string>("ApimKey"));
            restRequest.AddHeader("Content-Type", "application/json");

            ScraperRequest requestObject = new ScraperRequest()
            {
                url = url
            };

            restRequest.AddJsonBody(requestObject);

            try
            {
                var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);

                return(JsonConvert.DeserializeObject <ScraperResponse>(response.Content));
            }
            catch (Exception)
            {
                throw;
            }
        }
        private async Task <bool> ResetItem()
        {
            DocLine doc = (await App.Database.GetSpecificDocsAsync(UsingDoc.DocNum)).Where(x => x.ItemCode == lastItem).FirstOrDefault();
            var     ds  = new DataSet();

            try
            {
                var     t1  = new DataTable();
                DataRow row = null;
                t1.Columns.Add("DocNum");
                t1.Columns.Add("ItemBarcode");
                t1.Columns.Add("ScanAccQty");
                t1.Columns.Add("Balance");
                t1.Columns.Add("ScanRejQty");
                t1.Columns.Add("PalletNumber");
                t1.Columns.Add("GRV");
                row                 = t1.NewRow();
                row["DocNum"]       = doc.DocNum;
                row["ItemBarcode"]  = doc.ItemBarcode;
                row["ScanAccQty"]   = 0;
                row["Balance"]      = 0;
                row["ScanRejQty"]   = 0;
                row["PalletNumber"] = 0;
                row["GRV"]          = false;
                t1.Rows.Add(row);
                ds.Tables.Add(t1);
                string myds = Newtonsoft.Json.JsonConvert.SerializeObject(ds);
                RestSharp.RestClient client = new RestSharp.RestClient();
                client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath);
                {
                    var Request = new RestSharp.RestRequest("SaveDocLine", RestSharp.Method.POST);
                    Request.RequestFormat = RestSharp.DataFormat.Json;
                    Request.AddJsonBody(myds);
                    var cancellationTokenSource = new CancellationTokenSource();
                    var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                    if (res.IsSuccessful && res.Content.Contains("COMPLETE"))
                    {
                        await restetQty(doc);

                        lblBalance.Text     = "0";
                        lblScanQTY.Text     = "";
                        lblOrderQTY.Text    = "";
                        lblitemDescAcc.Text = "";
                        PicImage.IsVisible  = false;
                        txfAccCode.Focus();
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
            }
            return(false);
        }
Example #13
0
        /// <summary>
        /// QRCode 생성을 위한 URL 요청
        /// </summary>
        /// <param name="aRfid"></param>
        /// <param name="aPurchaseHistoryOnetimeURL"></param>
        /// <returns></returns>
        public static DTOPurchaseHistoryOnetimeURLResponse API_PostPurchaseHistoryOnetimeURL(string aRfid, long aBeforeTimestamp, long aAfterTimestamp)
        {
            //----------------------------------------
            DTOPurchaseHistoryOnetimeURLRequest req = new DTOPurchaseHistoryOnetimeURLRequest();

            {
                req.rfid            = aRfid;
                req.purchase_before = aBeforeTimestamp;
                req.purchase_after  = aAfterTimestamp;
            }

            //----------------------------------------
            RestSharp.RestClient  client  = new RestSharp.RestClient(URL_DCCAFFE);
            RestSharp.RestRequest request = new RestSharp.RestRequest();
            request.AddHeader("Content-Type", "application/json;charset=UTF-8");

            request.Method        = RestSharp.Method.POST;
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.Resource      = URI_POST_PURCHASE_HISTORY_TEMPORARY_URL;
            request.AddJsonBody(req);

            //----------------------------------------
            var t1 = client.ExecuteTaskAsync(request);

            t1.Wait();

            //----------------------------------------
            // error handling
            if (t1.Result.ErrorException != null)
            {
                System.Diagnostics.Debug.WriteLine("[RESPONSE] " + t1.Result.Content);
                return(null);
            }

            string json = t1.Result.Content;

            //----------------------------------------
            // debug output
            json = JsonFormatting(json);
            System.Diagnostics.Debug.WriteLine("[RESPONSE] " + json);

            //----------------------------------------
            // desirialized json data
            DTOPurchaseHistoryOnetimeURLResponse dto = new DTOPurchaseHistoryOnetimeURLResponse();

            try
            {
                dto      = JsonConvert.DeserializeObject <DTOPurchaseHistoryOnetimeURLResponse>(json);
                dto.code = (int)t1.Result.StatusCode;
            }
            catch (Exception ex)
            {
                dto = null;
                System.Diagnostics.Debug.WriteLine("[ERROR] " + ex.Message);
            }

            return(dto);
        }
Example #14
0
        /// <summary>
        /// 구매 취소
        /// </summary>
        /// <param name="aReceiptId"></param>
        /// <returns></returns>
        public static DTOPurchaseCancelResponse API_PatchPurchaseCancel(string aRfid, string aReceiptId)
        {
            //----------------------------------------
            DTOPurchaseCancelRequest req = new DTOPurchaseCancelRequest();

            {
                req.rfid = aRfid;
            }

            //----------------------------------------
            RestSharp.RestClient  client  = new RestSharp.RestClient(URL_DCCAFFE);
            RestSharp.RestRequest request = new RestSharp.RestRequest();
            request.AddHeader("Content-Type", "application/json;charset=UTF-8");

            request.Method        = RestSharp.Method.PATCH;
            request.RequestFormat = RestSharp.DataFormat.Json;
            request.Resource      = URI_PATCH_PURCHASE_CANCEL;

            request.AddParameter("receipt_id", aReceiptId, RestSharp.ParameterType.UrlSegment);
            request.AddJsonBody(req);

            //----------------------------------------
            var t1 = client.ExecuteTaskAsync(request);

            t1.Wait();

            //----------------------------------------
            // error handling
            if (t1.Result.ErrorException != null)
            {
                System.Diagnostics.Debug.WriteLine("[RESPONSE] " + t1.Result.Content);
                return(null);
            }

            string json = t1.Result.Content;

            //----------------------------------------
            // debug output
            json = JsonFormatting(json);
            System.Diagnostics.Debug.WriteLine("[RESPONSE] " + json);

            //----------------------------------------
            // desirialized json data
            DTOPurchaseCancelResponse dto = new DTOPurchaseCancelResponse();

            try
            {
                dto      = JsonConvert.DeserializeObject <DTOPurchaseCancelResponse>(json);
                dto.code = (int)t1.Result.StatusCode;
            }
            catch (Exception ex)
            {
                dto = null;
                System.Diagnostics.Debug.WriteLine("[ERROR] " + ex.Message);
            }

            return(dto);
        }
Example #15
0
        private async Task <bool> SaveData()
        {
            var ds = new DataSet();

            try
            {
                var     t1  = new DataTable();
                DataRow row = null;
                t1.Columns.Add("DocNum");
                t1.Columns.Add("ItemBarcode");
                t1.Columns.Add("ScanAccQty");
                t1.Columns.Add("Balance");
                t1.Columns.Add("ScanRejQty");
                t1.Columns.Add("PalletNumber");
                t1.Columns.Add("GRV");
                string         s    = txfSOCode.Text.ToUpper();
                List <DocLine> docs = (await GoodsRecieveingApp.App.Database.GetSpecificDocsAsync(s)).ToList();
                foreach (string str in docs.Select(x => x.ItemDesc).Distinct())
                {
                    foreach (int ints in docs.Where(x => x.PalletNum != 0 && x.ItemDesc == str).Select(x => x.PalletNum).Distinct())
                    {
                        row                 = t1.NewRow();
                        row["DocNum"]       = docs.Select(x => x.DocNum).FirstOrDefault();
                        row["ScanAccQty"]   = docs.Where(x => x.PalletNum == ints && x.ItemDesc == str).Sum(x => x.ScanAccQty);
                        row["ScanRejQty"]   = 0;
                        row["ItemBarcode"]  = docs.Where(x => x.PalletNum == ints && x.ItemDesc == str).Select(x => x.ItemBarcode).FirstOrDefault();
                        row["Balance"]      = -1;
                        row["PalletNumber"] = ints;
                        row["GRV"]          = false;
                        t1.Rows.Add(row);
                    }
                }
                ds.Tables.Add(t1);
            }
            catch (Exception)
            {
                return(false);
            }
            string myds = Newtonsoft.Json.JsonConvert.SerializeObject(ds);

            RestSharp.RestClient client = new RestSharp.RestClient();
            client.BaseUrl = new Uri(GoodsRecieveingApp.MainPage.APIPath);
            {
                var Request = new RestSharp.RestRequest("SaveDocLine", RestSharp.Method.POST);
                Request.RequestFormat = RestSharp.DataFormat.Json;
                Request.AddJsonBody(myds);
                var cancellationTokenSource = new CancellationTokenSource();
                var res = await client.ExecuteAsync(Request, cancellationTokenSource.Token);

                if (res.IsSuccessful && res.Content.Contains("COMPLETE"))
                {
                    return(true);
                }
            }
            return(false);
        }
        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 LoginResponse Login()
        {
            var restClient = new RestSharp.RestClient("https://app.sharesies.nz/");

            RestSharp.RestRequest request = new RestSharp.RestRequest("api/identity/login", RestSharp.Method.POST);
            request.AddJsonBody(_options);
            var response = restClient.Execute <LoginResponse>(request);

            return(response.Data);
        }
Example #18
0
        public static async Task ReportMessage(Models.ReportDetails details, IConfiguration configuration)
        {
            client = new RestSharp.RestClient("https://we-sendfact-fa.azurewebsites.net");
            RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/api/messagearchive", RestSharp.Method.POST);

            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddJsonBody(details);

            await client.ExecuteAsync(restRequest).ConfigureAwait(false);
        }
        public async Task <T> Post <T>(string route, object requestBody, Dictionary <string, string> parameters = null)
        {
            route = ReplaceParams(route, parameters);

            var request = new RestSharp.RestRequest(route, RestSharp.Method.POST);

            request.AddJsonBody(requestBody);
            var response = rest.Execute <T>(request);

            return(response.Data);
        }
Example #20
0
        public async Task ReportMessage(Models.ReportDetails details)
        {
            client = new RestSharp.RestClient(configuration.GetValue <string>("ApimBaseUrl"));
            RestSharp.RestRequest restRequest = new RestSharp.RestRequest("we-fakenews-func/Insert", RestSharp.Method.POST);

            restRequest.AddHeader("Ocp-Apim-Subscription-Key", configuration.GetValue <string>("ApimKey"));
            restRequest.AddHeader("Content-Type", "application/json");
            restRequest.AddJsonBody(details);

            await client.ExecuteAsync(restRequest).ConfigureAwait(false);
        }
Example #21
0
        private static async Task SendExpense(decimal amount, string reason)
        {
            try
            {
                var client  = new RestSharp.RestClient();
                var content = new RestSharp.RestRequest(new Uri(SERVICE_URL), RestSharp.Method.POST)
                {
                    RequestFormat = RestSharp.DataFormat.Json
                };

                content.AddJsonBody(new
                {
                    Amount     = amount,
                    Reason     = reason,
                    LicenseKey = PASample.Wpf.App.LicenseKey,
                    Id         = Guid.NewGuid(),
                    Department = PASample.Wpf.App.Department
                });

                content.Resource = "api/Expense/Approve";
                client.BaseUrl   = new Uri(SERVICE_URL);
                var uri      = client.BuildUri(content);
                var response = await client.ExecuteTaskAsync(content);

                if (response.ResponseStatus != RestSharp.ResponseStatus.Completed)
                {
                    MessageBox.Show("Unknown Error Processing Request", "Error");
                    return;
                }

                var respStream  = response.Content;
                var js          = new Newtonsoft.Json.JsonSerializer();
                var expResponse = (ExpenseApprovalResponse)js.Deserialize(new Newtonsoft.Json.JsonTextReader(new StringReader(respStream)), typeof(ExpenseApprovalResponse));


                var msg = string.Empty;
                if (expResponse.Exception == null || string.IsNullOrEmpty(expResponse.Exception.Message))
                {
                    msg = "Your request was processed.";
                }
                else
                {
                    msg = "Your request was rejected because - " + expResponse.Exception.Message;
                }
                MessageBox.Show(msg, "Result");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error", "Error");
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
Example #22
0
        private RestSharp.IRestResponse ExecuteRequestViaRestSharp(IRequest request)
        {
            var rc = new RestSharp.RestClient(_testSettings.BaseUrl);
            var rr = new RestSharp.RestRequest(request.RelativeUrl, request.Method);

            if (request.Body != null)
            {
                rr.AddJsonBody(request.Body);
            }

            _logger.Information("{Event} {HttpMethod} {BaseUrl}{RelativeUrl} {@request}", "TestStartHttpRequest", request.Method, _testSettings.BaseUrl, request.RelativeUrl, request);
            return(rc.Execute(rr));
        }
Example #23
0
 /// <summary>
 /// 通知回调函数,支付宝要求返回success才表示收到异步通知
 /// </summary>
 /// <param name="content">回调内容</param>
 /// <returns></returns>
 internal string NotiyCallBack(string content)
 {
     try
     {
         _log.Info("通知回调函数 NotiyCallBack 开始");
         var dic = GetDic(content);
         //验证回调通知是否正确
         if (GetSignVeryfy(dic) && CheckParams(dic))
         {
             _log.Info("通知回调函数成功!");
             var payResultNotify = GetPayResultNotify(dic);
             //从body中把设备号切出来
             var arr   = payResultNotify.Body.Split('║');
             var devID = "";
             if (arr.Length > 0)
             {
                 devID = arr[0];
             }
             if (arr.Length > 1)
             {
                 payResultNotify.Body = arr[1];
             }
             var callBackUrl = "";
             //获取返回的设备ID
             foreach (var dev in _setting.BackNotifies)
             {
                 if (dev.DeviceID == devID)
                 {
                     callBackUrl = dev.NotifyUrl;
                     break;
                 }
             }
             var client  = new RestSharp.RestClient(callBackUrl);
             var request = new RestSharp.RestRequest("", RestSharp.Method.POST);
             request.RequestFormat = RestSharp.DataFormat.Json;
             request.AddJsonBody(payResultNotify);
             var response = client.Execute(request);
             return(response.Content.ToLower());
         }
         else
         {
             _log.Error("通知回调函数验证失败");
             return("fail");
         }
     }
     catch (Exception exc)
     {
         _log.Fatal(exc, exc.Message);
         return("fail");
     }
 }
Example #24
0
        public IEnumerable <Stock> GetStocks(IEnumerable <string> stockIds, string token)
        {
            var restClient = new RestSharp.RestClient("https://data.sharesies.nz/");

            RestSharp.RestRequest request = new RestSharp.RestRequest($"api/v1/instruments", RestSharp.Method.POST);
            request.AddHeader("authorization", $"Bearer {token}");
            request.AddJsonBody(new StockSearchRequest
            {
                instruments = stockIds
            });

            var response = restClient.Execute(request);

            return(JsonConvert.DeserializeObject <StockSearchResponse>(response.Content).instruments);
        }
Example #25
0
        public static RestSharp.IRestResponse <T> Execute <T>(string uri, RestSharp.Method method, object objJsonBody = null) where T : new()
        {
            var client  = new RestSharp.RestClient(uri);
            var request = new RestSharp.RestRequest(method);

            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("Content-Type", "application/json");

            if (objJsonBody != null)
            {
                request.AddJsonBody(objJsonBody);
            }

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

            return(response);
        }
Example #26
0
        public void CreateUserTest()
        {
            RestSharp.RestClient  clinet  = new RestSharp.RestClient("http://localhost:50235/api/user");
            RestSharp.RestRequest request = new RestSharp.RestRequest(RestSharp.Method.POST);
            User user = new User()
            {
                Id      = Guid.NewGuid(),
                Address = "123",
                Name    = "TH.Lee",
                Phone   = "0901293"
            };

            request.AddJsonBody(user);
            var isSuccess = clinet.Execute <bool>(request);

            Assert.IsTrue(isSuccess.Data);
        }
Example #27
0
        public static async Task <Models.FakeAPIResponse> GetFakeNews(string message)
        {
            message = message.Replace("/check", "");
            try
            {
                client = new RestSharp.RestClient("https://prod-56.westeurope.logic.azure.com");

                RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/workflows/73896dc86d9149058d3bd5234fb4ae86/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=MmoB-9jJt1DbB25AfNJis889rx8b9LbJDX0zJSCsmoM", RestSharp.Method.POST);

                restRequest.AddHeader("Content-Type", "application/json");

                bool result = Uri.TryCreate(message, UriKind.Absolute, out Uri uriResult) &&
                              uriResult.Scheme == Uri.UriSchemeHttp;

                Models.Request requestObject;
                if (result)
                {
                    requestObject = new Models.Request
                    {
                        url  = message,
                        text = string.Empty
                    };
                }
                else
                {
                    requestObject = new Models.Request
                    {
                        text = message,
                        url  = string.Empty
                    };
                }

                restRequest.AddJsonBody(requestObject);

                var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);

                return(JsonConvert.DeserializeObject <Models.FakeAPIResponse>(response.Content));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public RestSharp.IRestResponse GetRandomVerificationCode(List <string> classNames)
        {
            JsonObject json = new JsonObject();

            JsonArray arr = new JsonArray();

            foreach (var kvp in classNames)
            {
                arr.Add(kvp);
            }

            json.Add("classNames", arr);

            RestSharp.RestRequest request = new RestSharp.RestRequest("verificationcode", RestSharp.Method.POST);
            request.AddJsonBody(json);

            RestSharp.IRestResponse response = Execute(request);

            return(response);
        }
        public static async Task <string> Validate([ActivityTrigger] string request,
                                                   ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            try
            {
                client = new RestSharp.RestClient(Environment.GetEnvironmentVariable("CognitiveEndpoint"));

                RestSharp.RestRequest restRequest = new RestSharp.RestRequest("/text/analytics/v2.1/keyPhrases", RestSharp.Method.POST);


                restRequest.AddHeader("Ocp-Apim-Subscription-Key", Environment.GetEnvironmentVariable("CognitiveApiKey"));
                restRequest.AddHeader("Content-Type", "application/json");

                var doc = new Document
                {
                    id       = "1",
                    language = "de",
                    text     = request
                };

                var requestObject = new RootObject
                {
                    documents = new List <Document>()
                    {
                        doc
                    }
                };

                restRequest.AddJsonBody(requestObject);

                var response = await client.ExecuteAsync(restRequest).ConfigureAwait(false);

                return(response.Content);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #30
0
        public async Task <T> Post <T, K>(string url, K objecttosend)
        {
            try
            {
                var client  = new RestSharp.RestClient(url);
                var request = new RestSharp.RestRequest(RestSharp.Method.POST);
                request.AddJsonBody(objecttosend);
                System.Diagnostics.Debug.WriteLine(url);
                var response = await client.ExecuteTaskAsync(request);

                if (response != null)
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(response.Content));
                    }
                }
            }
            catch
            {
            }
            return(default(T));
        }