當前位置: 首頁>>代碼示例>>C#>>正文


C# RestClient.ExecuteAsync方法代碼示例

本文整理匯總了C#中RestSharp.RestClient.ExecuteAsync方法的典型用法代碼示例。如果您正苦於以下問題:C# RestClient.ExecuteAsync方法的具體用法?C# RestClient.ExecuteAsync怎麽用?C# RestClient.ExecuteAsync使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在RestSharp.RestClient的用法示例。


在下文中一共展示了RestClient.ExecuteAsync方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: RegisterPhone

        public void RegisterPhone(string id, string uri)
        {
            string responseResult;

            var client = new RestClient(Constants.Settings.Recipe_Service_Api_Url);
            client.CookieContainer = new CookieContainer();
            var request = new RestRequest("account/JsonLogin", Method.POST);
            request.AddParameter("UserName", Constants.Settings.UserName);
            request.AddParameter("Password", Constants.Settings.Password);

            client.ExecuteAsync(
                request,
                response =>
                {
                    responseResult = response.Content;

                    var newrequest = new RestRequest("api/Subscription", Method.POST);
                    newrequest.AddParameter("phoneId", id);
                    newrequest.AddParameter("channelUri", uri);
                    client.ExecuteAsync(
                        newrequest ,
                        newresponse =>
                        {
                            responseResult = newresponse.Content;
                        });
                });
        }
開發者ID:kalkie,項目名稱:WeeklyThaiRecipe-WP,代碼行數:27,代碼來源:PhoneRegistrationService.cs

示例2: checkAcess

        /// <summary>
        /// 發送HTTP請求
        /// </summary>
        /// <param name="CardID"></param>
        /// <param name="IP"></param>
        /// <param name="Direction"></param>
        /// 0:進口 1:出口
        private static void checkAcess(string CardID, string IP, int Direction)
        {
            string Key = "2kJ0Ry19WcyZ2NGDXPXYoQfNG5WRzgjWbAdq6m1E"; //指定的API Key,從配置文件中讀取
            //string site = "http://tagger.chinacloudsites.cn"; //可替換,從配置文件中讀取
            string site = "http://localhost:59329";

            var client = new RestClient();
            client.BaseUrl = new Uri(site);
            var request = new RestRequest();
            request.Method = Method.POST;
            request.Resource = "SwipeCard/Check";
            request.AddParameter("Key", Key);
            request.AddParameter("CardId", CardID);
            request.AddParameter("IP", IP);
            request.AddParameter("Direction", Direction);
            var invokeTime = DateTime.Now;//刷卡的時間
            // 異步查詢預約管理係統的API,根據返回值在回調函數中執行相關操作
            client.ExecuteAsync<Result>(request, response => {
                //在這裏寫是否執行發送指令打開門禁的命令的邏輯
                //response.Content為0或1
                if(response.Data == null)
                {
                    Console.WriteLine("發送請求失敗!");
                }
                else
                {
                    var result = response.Data;
                    Console.WriteLine(result.ResultCode == 1 ? "開門" : "不開門");
                    Console.WriteLine(String.Format("發送指令至門禁:{0}", IP));
                    var currentTime = DateTime.Now;//HTTP請求返回的時間
                    Console.WriteLine(String.Format("發送請求時間:{0},收到回複時間:{1}", invokeTime.ToString("HH:mm:ss"), currentTime.ToString("HH:mm:ss")));
                }
                //存儲本次刷卡事件至數據文件
            });
        }
開發者ID:GoalFriend,項目名稱:rrrrrrrest,代碼行數:42,代碼來源:Program.cs

示例3: GetBlogPosts

        // performs REST request to retrieve the 50 most recent posts
        // http://api.typepad.com/blogs/blogId/post-assets/@published/@recent.js

        public async static Task<AdnBlogPostCollection> GetBlogPosts(
            string blogDisplayName, 
            string blogId)
        {
            string baseUrl = 
                "http://api.typepad.com/blogs/" 
                + blogId + 
                "/post-assets/@published/";

            RestClient client = new RestClient(baseUrl);

            RestRequest request = new RestRequest
            {
                Resource = "@recent.js",
                Method = Method.GET,
            };

            IRestResponse response =
                await client.ExecuteAsync(request);

            // removes "callback{ ... }" component around reply
            string content = response.Content.Substring(
                9, response.Content.Length-17);

            // uses Linq to JSON
            JObject result = JObject.Parse(content);

            // 50 posts entries
            IList<JToken> entries = 
                result["entries"].Children().ToList();

            return new AdnBlogPostCollection(blogDisplayName, entries);
        }
開發者ID:DevNullx64,項目名稱:ADN-WinRT-Samples,代碼行數:36,代碼來源:AdnBlogManager.cs

示例4: LoadUrl

        private void LoadUrl()
        {
            try
            {
                RestRequest request = new RestRequest(URL.BASE3 + "APIv2/charityorganization/charity_program.php", Method.POST);

                request.AddHeader("content-type", "multipart/form-data");
                request.AddParameter("id_donors", Navigation.navIdDonors);
                request.AddParameter("token", Navigation.token);
                request.AddParameter("id_program", Navigation.idProgram);

                //calling server with restClient
                RestClient restClient = new RestClient();
                restClient.ExecuteAsync(request, (response) =>
                {
                    ShellToast toast = new ShellToast();
                    toast.Title = "Status Upload";
                    JObject jRoot = JObject.Parse(response.Content);
                    String result = jRoot.SelectToken("result").ToString();
                    JArray JItem = JArray.Parse(jRoot.SelectToken("item").ToString());

                    foreach (JObject item in JItem)
                    {
                       
                        Id_program = item.SelectToken("id_program").ToString();
                        Program_name = item.SelectToken("program_name").ToString();
                        Description = item.SelectToken("description").ToString();
                    }
                });
            }
            catch { }
        }
開發者ID:Handika-GEMkey,項目名稱:SolidareNew,代碼行數:32,代碼來源:ViewModelProgram.cs

示例5: GetPersons

 public void GetPersons(Action<List<Person>> callback)
 {
     var client = new RestClient("https://raw.github.com/bekkopen/dotnetkurs/master/PersonPhoneApp/");
     client.AddHandler("text/plain", new JsonDeserializer());
     var request = new RestRequest("Persons.json", Method.GET) {RequestFormat = DataFormat.Json};
     client.ExecuteAsync<List<Person>>(request, response => callback(response.Data));
 }
開發者ID:aasmundeldhuset,項目名稱:dotnetkurs,代碼行數:7,代碼來源:PersonsRestClient.cs

示例6: InitializeConnection

 private void InitializeConnection()
 {
     ucwaClient = new RestClient();
     request = new RestRequest(string.Format(autoDiscoverUrl, this.Domain));
     request.AddHeader("Accept", "application/json");
     ucwaClient.ExecuteAsync(request, this.ParseAutoDiscoveryResponse);
 }
開發者ID:nyghtrocker,項目名稱:Blog,代碼行數:7,代碼來源:UCWAHelper.cs

示例7: CreateTask

        //public string RESTServiceURL { get; set; }


        public RestResponse<CRMTask> CreateTask(CRMTask task, K2CRMConfig config)
        {
            var client = new RestClient(config.RESTUrl);

            var request = new RestRequest();
            request.Method = Method.POST;

            if (config.CredentialCache != null)
            {
                request.Credentials = config.CredentialCache;
            }
            if (config.Credentials != null)
            {
                request.Credentials = config.Credentials;
            }

            request.RequestFormat = RestSharp.DataFormat.Json;
            request.Resource = "K2CRM/CRMCreateTask";

            request.AddBody(task);
            RestResponse<CRMTask> response = null; 
            if (config.Async)
            {
                client.ExecuteAsync<CRMTask>(request, null);
            }
            else
            {
                response = client.Execute<CRMTask>(request);
            }
            return response;
        }
開發者ID:jonnoking,項目名稱:K2-Dynamics-CRM-Extensions,代碼行數:34,代碼來源:WizardFunctions.cs

示例8: btnSignIn_Click

 private void btnSignIn_Click(object sender, RoutedEventArgs e)
 {
     //NavigationService.Navigate(new Uri(string.Format("/PanoramicMain.xaml"), UriKind.Relative));
     user = tbLogin.Text.ToString();
     pass= passwordBox1.Password.ToString();
     char[] characters = { '"', '/' };
     var settings = IsolatedStorageSettings.ApplicationSettings;
     RestRequest request = new RestRequest("http://localhost:23790/WebService/MobileLogOn", Method.POST);
     request.AddParameter("user", user);
     request.AddParameter("pass", pass);
     //calling server with restClient
     RestClient restClient = new RestClient();
     restClient.ExecuteAsync(request, (response) =>
     {
         if (response.StatusCode == HttpStatusCode.OK)
         {
             //upload successfull
             if (!response.Content.Contains("error") && response != null)
             {
                 settings["tokken"] = response.Content.Trim(characters);
                // MessageBox.Show("Upload completed succesfully...\n" + response.Content);
                 NavigationService.Navigate(new Uri(string.Format("/PanoramicMain.xaml"), UriKind.Relative));
             }
             else
             {
                 MessageBox.Show("Credentials are not correct!");
             }
         }
         else
         {
             //error ocured during upload
             MessageBox.Show(response.StatusCode + "\n" + response.StatusDescription);
         }
     });
 }
開發者ID:marcin-owoc,項目名稱:TouristGuide,代碼行數:35,代碼來源:MainPage.xaml.cs

示例9: GetAccessTokenAsync

        public async Task<AccessToken> GetAccessTokenAsync(RequestToken requestToken, string verifier)
        {
            if (requestToken == null) throw new InvalidOperationException("Cannot get the Access token without a Request token.");
            if (verifier == null) throw new InvalidOperationException("Cannot get the Access token without a verifer");

            if (string.IsNullOrWhiteSpace(verifier))
                throw new Exception("There was no oauth_verifier parameter on the callback request.");

            var client =
                new RestClient(_apiBaseUrl)
                {
                    Authenticator = OAuth1Authenticator.ForAccessToken(_consumerKey, _consumerSecret, requestToken.Value, requestToken.Secret, verifier)
                };
            var request = new RestRequest(AccessTokenPath);
            var response = await client.ExecuteAsync(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var queryString = HttpUtility.ParseQueryString(response.Content);
                var accessToken = new AccessToken(queryString["oauth_token"], queryString["oauth_token_secret"]);
                return accessToken;
            }

            throw new Exception("An error occured: Status code: " + response.StatusCode, response.ErrorException);
        }
開發者ID:highwaychurch,項目名稱:web,代碼行數:25,代碼來源:PCOAuthorizationService.cs

示例10: GetData

        public  void  GetData(string city, string country)
        {
            RepositoryHolder holder = new RepositoryHolder();
            string type = "Банк";
            var client = new RestClient("https://search-maps.yandex.ru/v1/?text=" + type + ", " + city + ", " + country + "&type=biz&lang=uk_Ua&apikey=f7f27aa0-8bf2-4d7d-9e80-fdab701a58c8&results=500");

            var request = new RestRequest("resource/", Method.GET);

            var asyncHandle = client.ExecuteAsync<YandexModel.RootObject>(request, response =>
            {


                for (int i = 0; i <= response.Data.features.Count - 1; i++)
                {
                    string[] buf = response.Data.features[i].properties.CompanyMetaData.address.Split(','); //разбиваем строку на массив слов, разделитель пробел

                    Char separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
                    String Source = response.Data.features[i].geometry.coordinates[0].Replace(',', separator);
                    Double number = Convert.ToDouble(Source);
                    String Source2 = response.Data.features[i].geometry.coordinates[1].Replace(',', separator);
                    Double number2 = Convert.ToDouble(Source2);
                    holder.AdressRepository.Insert(new Entity.tbAdress()
                    {
                        cLatitude = Source,
                        cLongitude = Source2,
                        cIdBank = 1,
                        cAdressVal = response.Data.features[i].properties.CompanyMetaData.address,
                        cCity = city,
                        cCountry = country,
                        cStreet = buf[1] + buf[2]
                    });
                    holder.SaveChanges();
                }
            });
        }
開發者ID:GoGo228,項目名稱:HIREpo,代碼行數:35,代碼來源:YandexGetBankByAdressStrategy.cs

示例11: EmailSubmit

 public static void EmailSubmit(string email, string code)
 {
     RestClient client = new RestClient();
     client.BaseUrl = "https://api.mailgun.net/v2";
     client.Authenticator =
             new HttpBasicAuthenticator("api",
                                        "key-032hr3-4h-s2w-esvcatgkvrra5kubs1");
     RestRequest request = new RestRequest();
     request.AddParameter("domain",
                          "nocompany.azurewebsites.net", ParameterType.UrlSegment);
     request.Resource = "{domain}/messages";
     request.AddParameter("from", "Idodil Agency <[email protected]>");
     request.AddParameter("to", email);
     request.AddParameter("subject", "Idodil");
     request.AddParameter("html",
         "<html><p>" + GlobalRes.MailerHello +
         "</p><p>" + GlobalRes.MailerEmailNotify +
         "</p><p>" + GlobalRes.MailerEmailBody +
         "</p><p><a href='" + "http://www.idodil.com/account/emailsubmit?token=" + code +"'>"+GlobalRes.EmailSubmitButton+"</a>"+
         "</p><p>" + GlobalRes.MailerEmailFill + code +
         "</p><p>" + GlobalRes.MailerBye +
         "</p></html>");
     request.Method = Method.POST;
     client.ExecuteAsync(request, response =>
     {
         var resp = response.Content;
     });
 }
開發者ID:kioltk,項目名稱:mvc,代碼行數:28,代碼來源:Mailer.cs

示例12: PushStatus

 /// <summary>
 /// Push the current environment status to clients.
 /// </summary>
 public void PushStatus()
 {
     var command = new EnvironmentCommand { Command = EnvironmentCommands.Status }.ToPostUrl();
     var client = new RestClient(Host);
     var request = new RestRequest(command, Method.POST);
     client.ExecuteAsync(request, response => {});
 }
開發者ID:hhandoko,項目名稱:akka-dotnet-ddd,代碼行數:10,代碼來源:RestServiceController.cs

示例13: GetUserBadgeInformation

 // "https://verrechnungsportal.hsr.ch:4450/VerrechnungsportalService.svc/JSON/getBadgeSaldo"
 public static void GetUserBadgeInformation(UserCredentials userCredentials, BadgeInformationCallback callback)
 {
     var b = new BackgroundWorker();
     b.DoWork += (sender, args) =>
     {
         if (userCredentials.CredentialsFilled)
         {
             System.Net.ServicePointManager.ServerCertificateValidationCallback += (s, certificate, chain, sslPolicyErrors) => true;
             var restClient = new RestClient(BadgeportalUrl);
             restClient.Authenticator = new HttpBasicAuthenticator(userCredentials.DomainName, userCredentials.Password);
             restClient.ExecuteAsync(new RestRequest("/getBadgeSaldo", Method.GET), (response, handle) =>
             {
                 try
                 {
                     var badgeportal = JsonHelper.ParseJson<BadgeInformation>(response);
                     callback(badgeportal);
                 } catch (Exception e)
                 {
                     callback(new BadgeInformation(){ErrorMessage = e.Message});
                 }
             });
         }
         else
         {
             callback(new BadgeInformation(){ CashAmount = 0 });
         }};
     b.RunWorkerAsync();
 }
開發者ID:buehler,項目名稱:xamarin-hsr-challenge-project,代碼行數:29,代碼來源:DomainLibraryHelper.cs

示例14: GetSchedule

        public void GetSchedule()
        {
            RestClient client = new RestClient(serviceUri);

            RestRequest request = new RestRequest("/universities/1/faculties/1/groups/1/timetable.json", Method.GET);
            request.RequestFormat = DataFormat.Json;
            client.ExecuteAsync(request, (response) =>
            {
                try
                {
                    if (response.ResponseStatus == ResponseStatus.Completed)
                    {
                        string responseContent = response.Content;
                        List<LessonJson> lessonsJson = JsonConvert.DeserializeObject<List<LessonJson>>(responseContent);
                        List<Lesson> lessons = new List<Lesson>();
                        foreach (LessonJson lsj in lessonsJson)
                        {
                            Lesson ls = new Lesson(lsj);
                            lessons.Add(ls);
                        }
                        List<Group<Lesson>> grLessons = CustomKeyGroup<Lesson>.GetLessonsGroups(lessons);
                        if (Callback != null)
                        {
                            Callback(grLessons);
                        }

                    }
                }
                catch (Exception exc)
                {
                    //MessageBox.Show(exc.Message);
                }
            });
        }
開發者ID:scheduleby,項目名稱:Schedule-WP,代碼行數:34,代碼來源:NetworkEngine.cs

示例15: OpenURL

		public void OpenURL (string url, bool isPost, CookieContainer cookieJar=null)
		{

			var client = new RestClient ();
			client.CookieContainer = cookieJar;

			var request = new RestRequest (url, isPost ? Method.POST : Method.GET) { RequestFormat = DataFormat.Json };

			AddNetworkActivity (url);

			client.ExecuteAsync (request, response => {
				if(response.Cookies.Count > 0){
					if(response.Cookies[0].Name == "_whitepaperbible_session"){
						UserSessionCookie = new SessionCookie{ 
							Name = response.Cookies[0].Name,
							Value = response.Cookies[0].Value
						};
					}
				}

				ResponseText = response.Content;
				RemoveNetworkActivity (url);
				if (response.ResponseStatus == ResponseStatus.Error) {
					DispatchError ();
				} else {
					DispatchComplete ();
				}
			});
		}
開發者ID:davidortinau,項目名稱:WhitePaperBibleMono,代碼行數:29,代碼來源:WebClient.cs


注:本文中的RestSharp.RestClient.ExecuteAsync方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。