当前位置: 首页>>代码示例>>C#>>正文


C# RestSharp.RestClient类代码示例

本文整理汇总了C#中RestSharp.RestClient的典型用法代码示例。如果您正苦于以下问题:C# RestClient类的具体用法?C# RestClient怎么用?C# RestClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


RestClient类属于RestSharp命名空间,在下文中一共展示了RestClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ActivateFeature

        public string ActivateFeature(string baseSiteUrl, string user, string password, string domain)
        {
            if (baseSiteUrl.EndsWith("/"))
                baseSiteUrl += "_api/";
            else
                baseSiteUrl += "/_api/";

            RestClient rc = new RestClient(baseSiteUrl);
            NetworkCredential nCredential = new NetworkCredential(user, password, domain);
            rc.Authenticator = new NtlmAuthenticator(nCredential);

            RestRequest request = new RestRequest("contextinfo?$select=FormDigestValue", Method.POST);
            request.AddHeader("Accept", "application/json;odata=verbose");
            request.AddHeader("Body", "");

            string returnedStr = rc.Execute(request).Content;
            int startPos = returnedStr.IndexOf("FormDigestValue", StringComparison.Ordinal) + 18;
            int length = returnedStr.IndexOf(@""",", startPos, StringComparison.Ordinal) - startPos;
            string formDigestValue = returnedStr.Substring(startPos, length);

            request = new RestRequest("web/features/add('de646322-53f3-474d-96bf-0ea3670a0722',false)", Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Accept", "application/json;odata=verbose");
            //request.AddHeader("Body", "");
            request.AddHeader("Content-Type", "application/json;odata=verbose");
            request.AddHeader("X-RequestDigest", formDigestValue);
            IRestResponse response = rc.Execute(request);
            string content = response.Content;

            return content;
        }
开发者ID:PoojaDhingra,项目名称:ArchivalServicesRepo,代码行数:31,代码来源:WebService2.asmx.cs

示例2: IsValidKey

        public async Task<bool> IsValidKey(string key)
        {
            try
            {
                var client = new RestClient("http://" + _serverAdress);
                var request = new RestRequest("getProductKeyValid.php", Method.GET);
                request.AddParameter("productkeys_Key", key);

                request.Timeout = 5000;
                IRestResponse response = await client.ExecuteGetTaskAsync(request);
                //only throws the exception. Let target choose what to do
                if (response.ErrorException != null)
                {
                    throw response.ErrorException;
                }
                var model = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(response.Content);
                //if string equals "1" the key is not activated yet
                if (model.Equals("1"))
                    return true;
                return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }
开发者ID:Kundentelefon,项目名称:SMK,代码行数:26,代码来源:DataAccessMySqlPhp.cs

示例3: SignIn

        public RedirectResult SignIn(string login, string password, string appId, 
            string redirectUri, string state)
        {
            var client = new RestClient(SiteConn.AuthWebApiServer);
           

            var signInRequest = new RestRequest("Auth/SignIn");

            signInRequest.AddQueryParameter("login",login);
            signInRequest.AddQueryParameter("password",password);
            signInRequest.AddQueryParameter("appId",appId);
            signInRequest.AddQueryParameter("redirectUri", redirectUri);
            signInRequest.AddQueryParameter("state","666");

            var response = client.Post(signInRequest);
            if (response == null) return new RedirectResult(redirectUri);

            //получаю куки с токеном
            if (response.Cookies != null)
            {
                return new RedirectResult(redirectUri);
            }
            
            return null;
        }
开发者ID:Trigun27,项目名称:rsoi_lab3.FrontEnd,代码行数:25,代码来源:AuthMvcController.cs

示例4: InitRestClient

 private static void InitRestClient()
 {
     if (client==null)
     {
         client = new RestClient(SERVER_REST_URL);
     }
 }
开发者ID:TomasKulhanek,项目名称:Physio.FmiRestService,代码行数:7,代码来源:DymosimJSONProxy.cs

示例5: CreateInstance

        public void CreateInstance(string code)
        {
            var client = new RestClient("https://console.cloud-elements.com/elements/api-v2");
            var dropbox = "/elements/dropbox/instances";

            var json = @"{
             ""element"": {
               ""key"": ""dropbox""
             },
             ""providerData"": {
               ""code"": """ + code +  @"""
             },
             ""configuration"": {
               ""oauth.callback.url"": ""http://localhost:40669/dropbox"",
               ""oauth.api.key"": ""oaivbq19cgkoia8"",
               ""oauth.api.secret"": ""t6c5spexx0g5fuk"",
               ""document.tagging"": false
             },
             ""tags"": [
               ""test""
             ],
             ""name"": ""hui-test-" + new Random().Next() + @"""
            }";
            var createInstance = new RestRequest(dropbox, Method.POST) { RequestFormat = DataFormat.Json };
            createInstance.AddHeader("Authorization", "User kiJp+N8I12IAynsqCqq4I7M/XuwS6aUSJR4hLPLYCI8=, Organization 1eaea1a56a443c25f529ca678c4cd66b");

            //createInstance.AddParameter("elementInstance",json,  "application/json",  ParameterType.RequestBody);
            createInstance.AddParameter("application/json", json, ParameterType.RequestBody);
            //            createInstance.AddBody(json);

            var restResponse = client.Execute(createInstance);
            var restfulResponse = new RestfulResponse(restResponse, dropbox);
        }
开发者ID:Rallyteam,项目名称:Geoffrey,代码行数:33,代码来源:DropboxService.cs

示例6: getStartups

        public StartupList getStartups(StartupFilter filter)
        {
            var client = new RestClient(StaticValues.RootUri);

            var request = new RestRequest("startups", Method.GET);
            request.AddParameter("filter", StringEnum.GetStringValue(filter));

            var response = client.Execute(request);
            var content = response.Content;

            // Check Errros
            ErrorChecker.CheckForErrors(response, 1);

            if (filter != StartupFilter.Raising)
            {
                var startupsObj = JsonConvert.DeserializeObject<List<Startup>>(content.Replace(",\"fundraising\":false", "").Replace(",\"fundraising\":true", ""));

                return new StartupList()
                {
                    Startups = startupsObj,
                    LastPage = 1,
                    Total = startupsObj.Count,
                    PerPage = 50,
                    Page = 1
                };

            } else {

                var startupsObj = JsonConvert.DeserializeObject<StartupList>(content);
                return startupsObj;
            }
        }
开发者ID:skraloupak,项目名称:AngelList,代码行数:32,代码来源:StartupRepository.cs

示例7: authorization

        /// <summary>
        /// Authorizes app via twitch.tv. If successful redirect is generated and code is parsed
        /// </summary>
        /// <returns></returns>
        public Code authorization()
        {
            {
                var client = new RestClient(@"https://api.twitch.tv/kraken/oauth2/authorize");
                var request = new RestRequest(Method.GET);

                request.AddParameter("response_type", "code");
                request.AddParameter("client_id", ClientID);
                request.AddParameter("redirect_url", @"https://localhost");
                request.AddParameter("scope", "chat_login");
                request.AddParameter("state", state);

                var response = client.Execute(request);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //somehow grab redirect and parse code...

                }
                else
                {
                    return null;
                }
            }
        }
开发者ID:ChristenBowies,项目名称:Twitch-Dashboard-Client,代码行数:29,代码来源:Authorization.cs

示例8: download

        static private async Task<Images> download(string domain, string path, string pattern)
        {
            var result = new Images();
            var client = new RestClient(domain);
            var restTasks = new List<Task<IRestResponse>>();
            var response = client.Get(new RestRequest(path, Method.GET));

            foreach (Match match in Regex.Matches(response.Content, pattern))
            {
                string fileName = match.Captures[0].Value.Replace(">", "");
                result.Add(fileName, 0);
                if (!File.Exists(baseDir(path) + "\\" + fileName))
                {
                    var img = new RestRequest(path + fileName, Method.GET);
                    img.AddParameter("fileName", fileName);
                    restTasks.Add(client.ExecuteTaskAsync(img));
                }
            }

            foreach (var restTask in restTasks)
            {
                response = await restTask;
                string fileName = response.Request.Parameters[0].Value.ToString();
                result[fileName] = (int)response.StatusCode;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var fs = File.Create(baseDir(path) + "\\" + fileName);
                    await fs.WriteAsync(response.RawBytes, 0, response.RawBytes.Length);
                    fs.Close();
                }
            }
            return result;
        }
开发者ID:heldersepu,项目名称:csharp-proj,代码行数:33,代码来源:DownloadController.cs

示例9: 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

示例10: CustomDataHelper

 public CustomDataHelper(string site, string user, string password, string baseUrl)
 {
     _client = new RestClient(baseUrl)
                   {
                       Authenticator = new HttpBasicAuthenticator(site + "\\" + user, password)
                   };
 }
开发者ID:jsermini,项目名称:eloqua-samples,代码行数:7,代码来源:CustomDataHelper.cs

示例11: GetAuthUrlToken

        /// <summary>
        /// Use this method first to retrieve the url to redirect the user to to allow the url.
        /// Once they are done there, Fitbit will redirect them back to the predetermined completion URL
        /// </summary>
        /// <returns></returns>
        public string GetAuthUrlToken()
        {
			var baseUrl = "https://api.fitbit.com";
			var client = new RestClient(baseUrl);
			client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret);
            
            var request = new RestRequest("oauth/request_token", Method.POST);
			var response = client.Execute(request);


			//Assert.NotNull(response);
			//Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            if(response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new Exception("Request Token Step Failed");

			var qs = HttpUtility.ParseQueryString(response.Content);
			var oauth_token = qs["oauth_token"];
			var oauth_token_secret = qs["oauth_token_secret"];

			//Assert.NotNull(oauth_token);
			//Assert.NotNull(oauth_token_secret);

			request = new RestRequest("oauth/authorize");
			request.AddParameter("oauth_token", oauth_token);
			var url = client.BuildUri(request).ToString();
			//Process.Start(url);

            return url;
        }
开发者ID:Aaronontheweb,项目名称:Fitbit.NET,代码行数:35,代码来源:Authenticator.cs

示例12: TeamCityClient

        public TeamCityClient(string username, string password, string serverUrl)
        {
            _username = username;
            _password = password;

            _restClient = new RestClient(serverUrl) { Authenticator = new HttpBasicAuthenticator(_username, _password) };
        }
开发者ID:AlexShkorParalect,项目名称:TeamCitySharper,代码行数:7,代码来源:TeamCityClient.cs

示例13: SearchButton_Click

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            RestClient client = new RestClient("http://pokeapi.co/api/v1");

            string pokemonName = PokemonNameBox.Text;

            RestRequest request = new RestRequest("pokemon/{name}", Method.GET);
            request.AddUrlSegment("name", pokemonName);
            var response = client.Execute(request);

            if (response.Content == "")
            {
                ResultBox.AppendText(String.Format("Pokemon {0} not found{1}",pokemonName,Environment.NewLine));
            }

            dynamic pokemon = JsonConvert.DeserializeObject(response.Content);

            bool hasEvolution = (pokemon.evolutions.Count > 0) ? true : false;

            if (hasEvolution)
            {
                ResultBox.AppendText(String.Format("{0} has an evolution!{1}", pokemonName,Environment.NewLine));
                ResultBox.AppendText(String.Format("Method of evolution: {0}{1}", pokemon.evolutions[0].method, Environment.NewLine));
            }
            else
            {
                ResultBox.AppendText(String.Format("{0} has no evolution.{1}", pokemonName,Environment.NewLine));
            }

            ResultBox.AppendText(Environment.NewLine);
        }
开发者ID:NoahSanders,项目名称:Pokemon,代码行数:31,代码来源:MainWindow.xaml.cs

示例14: cargarKPIsAsignados

        private void cargarKPIsAsignados()
        {
            RestClient client = new RestClient(ConfigurationManager.AppSettings.Get("endpoint"));
            RestRequest request = new RestRequest("kpis/indicadoresAsignados/{idRol}", Method.GET);

            request.AddUrlSegment("idRol", (string)Session["idRolSeleccionado"]);

            var response = client.Execute(request);

            string json = response.Content;

            List<KPI> listaKpis = JsonConvert.DeserializeObject<List<KPI>>(json);

            if (listaKpis != null)
            {
                DataTable tablaIndicadoresKPIAsignados = new DataTable("kpis");
                tablaIndicadoresKPIAsignados.Columns.AddRange(new DataColumn[5] {new DataColumn("ID",typeof(int)),
                new DataColumn("Descripcion",typeof(string)),
                new DataColumn("Formato",typeof(string)),
                new DataColumn("Objetivo",typeof(string)),
                new DataColumn("Periodicidad",typeof(string))
                });
                if (listaKpis.Count > 0)
                    foreach (var kpi in listaKpis)
                        tablaIndicadoresKPIAsignados.Rows.Add(kpi.KPIID, kpi.DescKpi, kpi.Formato, kpi.Objetivo, kpi.Periodicidad);

                Session["indicadoresKPIAsignados"] = tablaIndicadoresKPIAsignados;
                bindData(false);
            }
        }
开发者ID:jimmivco,项目名称:AspProyectoKPIs,代码行数:30,代码来源:asignarIndicadoresKPI.aspx.cs

示例15: Get

 public IEnumerable<Event> Get()
 {
     var client = new RestClient(@"https://github.com");
     var request = new RestRequest(string.Format("{0}.json", _username));
     var response = client.Execute(request);
     return JsonConvert.DeserializeObject<IList<Event>>(response.Content);
 }
开发者ID:jwright,项目名称:github-fantasy-league-dotnet-old,代码行数:7,代码来源:EventParser.cs


注:本文中的RestSharp.RestClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。