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


C# RestClient.BuildUri方法代码示例

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


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

示例1: GetMarketCategories

        private IEnumerable<MarketCategory> GetMarketCategories()
        {
            if (_marketCategoriesCache == null)
            {
                var client = new RestClient("http://network.adsmarket.com/site/API2");

                client.DefaultParameters.Add(new Parameter { Name = "userid", Value = ConfigurationManager.AppSettings["SuperMarketApiUserId"], Type = ParameterType.QueryString });
                client.DefaultParameters.Add(new Parameter { Name = "uid", Value = ConfigurationManager.AppSettings["SuperMarketApiUserId"], Type = ParameterType.QueryString });
                client.DefaultParameters.Add(new Parameter { Name = "key", Value = ConfigurationManager.AppSettings["SuperMarketApiKey"], Type = ParameterType.QueryString });

                var request = new RestRequest();
                request.AddParameter("fn", "getcategories");

                var response = client.Execute<CategoryList>(request);

                if (response == null)
                {
                    throw new Exception(String.Format("Failed to communicate with MarketApi: {0} Response: {1}", client.BuildUri(request), response.Content));
                }
                if (response.Data == null)
                {
                    throw new Exception(String.Format("Failed to communicate with MarketApi: {0} No response", client.BuildUri(request)));
                }
                var cats = response.Data.Categories.ToArray();

                _marketCategoriesCache = cats.Select(c => new MarketCategory() { Id = c.CategoryId, Name = c.CategoryTitle });
            }

            return _marketCategoriesCache;
        }
开发者ID:c0d3m0nky,项目名称:mty,代码行数:30,代码来源:RetargetingController.cs

示例2: LogRequest

        private void LogRequest(RestClient restClient, IRestRequest request, IRestResponse response, long durationMs)
        {
            var requestToLog = new
            {
                resource = request.Resource,
                // Parameters are custom anonymous objects in order to have the parameter type as a nice string
                // otherwise it will just show the enum value
                parameters = request.Parameters.Select(parameter => new
                {
                    name = parameter.Name,
                    value = parameter.Value,
                    type = parameter.Type.ToString()
                }),
                // ToString() here to have the method as a nice string otherwise it will just show the enum value
                method = request.Method.ToString(),
                // This will generate the actual Uri used in the request
                uri = restClient.BuildUri(request),
            };

            var responseToLog = new
            {
                statusCode = response.StatusCode,
                content = response.Content,
                headers = response.Headers,
                // The Uri that actually responded (could be different from the requestUri if a redirection occurred)
                responseUri = response.ResponseUri,
                errorMessage = response.ErrorMessage,
            };

            Trace.Write(string.Format("Request completed in {0} ms, Request: {1}, Response: {2}",
                    durationMs,
                    JsonConvert.SerializeObject(requestToLog),
                    JsonConvert.SerializeObject(responseToLog)));
        }
开发者ID:CactusSoft,项目名称:Cactus.Fileserver,代码行数:34,代码来源:CrudIntegrationTest.cs

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

示例4: GenerateAuthUrlToken

		private string GenerateAuthUrlToken(bool forceLogoutBeforeAuth)
		{
			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);

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

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

			if(forceLogoutBeforeAuth)
				request = new RestRequest("oauth/logout_and_authorize"); //this url will force the user to type in username and password
			else
				request = new RestRequest("oauth/authorize");           //this url will show allow/deny if a user is currently logged in
			request.AddParameter("oauth_token", RequestToken);
			var url = client.BuildUri(request).ToString();

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

示例5: Can_Authenticate_With_OAuth

        public void Can_Authenticate_With_OAuth()
        {
            const string consumerKey = "HEGlGLuqfR1Aa8CwJNB0sw";
            const string consumerSecret = "D4UC98WMZbPaLztm47b7TwktQBiPhqpqJUd99hPhqw";

            var baseUrl = "http://api.twitter.com";
            var client = new RestClient(baseUrl);
            client.Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);
            // Token anfragen für Authorisierung
            var request = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

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

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

            // mit Authorisierungs-PIN ein Zugriffs-Token anfordern
            var verifier = "8083248"; // <-- Breakpoint here (set verifier in debugger)
            request = new RestRequest("oauth/access_token", Method.POST);
            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, oauth_token, oauth_token_secret, verifier
                );
            response = client.Execute(request);

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

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

            request = new RestRequest("1.1/statuses/user_timeline.json");
            request.AddParameter("count", 30);
            client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                consumerKey, consumerSecret, oauth_token, oauth_token_secret
                );

            var typedResponse = client.Execute<List<Tweet>>(request);
            var tweets = typedResponse.Data;

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            Assert.IsNotNull(tweets);
            Assert.IsTrue(tweets.Count > 0);
        }
开发者ID:Gope,项目名称:DDC_SampleCode,代码行数:59,代码来源:RestSharpSamples.cs

示例6: GenerateAuthUrlFromRequestToken

 public string GenerateAuthUrlFromRequestToken(RequestToken token)
 {
     RestRequest request = null;
     request = new RestRequest(token.Token + "/");
     var authclient = new RestClient(AuthorizeUrl);
     var url = authclient.BuildUri(request).ToString();
     return url;
 }
开发者ID:RC7502,项目名称:FortyTwoGoals.NET,代码行数:8,代码来源:Authenticator.cs

示例7: TestPort_AllowsChangingPort_InCaseOfConflictInTheMachineRunningTests

        public void TestPort_AllowsChangingPort_InCaseOfConflictInTheMachineRunningTests()
        {
            var client = new RestClient(BaseUrl.ToString());
            var request = new RestRequest("/echo", Method.GET);

            var response = client.Execute(request);
            var uri = client.BuildUri(response.Request);

            Assert.That(uri.Port, Is.EqualTo(49160));
        }
开发者ID:dgg,项目名称:testing-commons,代码行数:10,代码来源:HostTesterBaseTester.cs

示例8: HomePage_WhenCalled_ShouldContainHelloWorld

		public void HomePage_WhenCalled_ShouldContainHelloWorld()
		{
			// arrange
			Setup();
			// assert
			var client = new RestClient(BaseUri);
			var request = new RestRequest("", Method.GET);
			_log.Info("Placing request to " + client.BuildUri(request));
			IRestResponse executeTaskAsync = client.Execute(request);
			Console.Out.WriteLine("executeTaskAsync.Content:" + executeTaskAsync.Content);
			executeTaskAsync.Content.Should().Contain("Hello World!");
		}
开发者ID:rolfwessels,项目名称:DarthVaderBuildIndicator,代码行数:12,代码来源:RemoteApiTests.cs

示例9: Authenticate_UrlParameters_ShouldSucceed

        public void Authenticate_UrlParameters_ShouldSucceed( )
        {
            const string ROUTE = "/d2l/api/{foo}/{bar}";

            var client = new RestClient( BASE_ROUTE );
            var request = new RestRequest( ROUTE );
            request.AddUrlSegment( "foo", "abc" );
            request.AddUrlSegment( "bar", "xyz" );

            m_authenticator.Authenticate( client, request );

            string expectedUrl = GenerateExepctedUrl( "/d2l/api/abc/xyz" );
            Assert.AreEqual( expectedUrl, client.BuildUri(request).PathAndQuery );
        }
开发者ID:Brightspace,项目名称:valence-sdk-dotnet-restsharp,代码行数:14,代码来源:AuthenticatorTests.cs

示例10: Authenticate_UrlAndQueryParameters_ShouldSucceed

        public void Authenticate_UrlAndQueryParameters_ShouldSucceed( )
        {
            const string ROUTE = "/d2l/api/lp/{version}/users/";
            const string VERSION = "1.4";

            var client = new RestClient( BASE_ROUTE );
            var request = new RestRequest( ROUTE );
            request.AddUrlSegment( "version", VERSION );
            request.AddParameter( "userName", "user name" );

            m_authenticator.Authenticate( client, request );

            string expectedUrl = GenerateExepctedUrl( ROUTE.Replace( "{version}", VERSION ) + "?userName=user%20name" );

            Assert.AreEqual( expectedUrl, client.BuildUri(request).PathAndQuery );
        }
开发者ID:Brightspace,项目名称:valence-sdk-dotnet-restsharp,代码行数:16,代码来源:AuthenticatorTests.cs

示例11: Main

        private static void Main(string[] args)
        {
            using (var output = new StreamWriter(@"..\..\results.txt")) {
                foreach (var ep in endpoints) {
                    var url = String.Format("http://restival.local/api.{0}", ep);
                    var client = new RestClient(url);
                    var request = new RestRequest("whoami");
                    request.AddHeader("Accept", "application/json");
                    request.Credentials = new NetworkCredential("bob", "hope");
                    Console.WriteLine(client.BuildUri(request));
                    var response = client.Execute<WhoAmIResponse>(request);

                    output.WriteLine(ep);
                    output.WriteLine(response.Content);
                    output.WriteLine(String.Empty.PadLeft(72, '='));
                }
            }
        }
开发者ID:chenzuo,项目名称:Restival,代码行数:18,代码来源:Program.cs

示例12: Authenticate_QueryParameters_ShouldSucceed

        public void Authenticate_QueryParameters_ShouldSucceed(
				[Values(
					"/api/versions/", 
					"/api/collection/resource/?sort=asc", 
					"/api/versions?sort=asc",
					"/api/versions/?sort=asc&count=10",
					"/api/collection/resource?sort=asc&count=10")]string pathAndQuery
			)
        {
            var client = new RestClient( BASE_ROUTE );

            var request = new RestRequest( pathAndQuery );

            m_authenticator.Authenticate( client, request );

            string expectedUrl = GenerateExepctedUrl( pathAndQuery );

            Assert.AreEqual( expectedUrl, client.BuildUri(request).PathAndQuery );
        }
开发者ID:Brightspace,项目名称:valence-sdk-dotnet-restsharp,代码行数:19,代码来源:AuthenticatorTests.cs

示例13: LoginAsync

        public async Task<Token> LoginAsync(WebBrowser browser)
        {
            // Check for network connectivity
            if (!NetworkInterface.GetIsNetworkAvailable()) return null;

            var client =
                new RestClient("https://api.twitter.com/oauth/")
                {
                    FollowRedirects = true,
                    Authenticator = OAuth1Authenticator.ForRequestToken(_consumerKey, _consumerSecret)
                };

            var requestToken = await GetRequestToken(client);

            var uri = client.BuildUri(
                new RestRequest("authorize")
                    .AddParameter("oauth_token", requestToken["oauth_token"]));
            var verifier = await GetVerifier(browser, uri);

            client.Authenticator =
                OAuth1Authenticator.ForAccessToken(
                    _consumerKey, _consumerSecret,
                    requestToken["oauth_token"], requestToken["oauth_token_secret"],
                    verifier["oauth_verifier"]);
            var accessToken = await GetAccessToken(client);

            Debug.Assert(requestToken["oauth_token"] == verifier["oauth_token"]);

            InsertOrUpdateToken(
                new Token
                {
                    Id = int.Parse(accessToken["user_id"]),
                    Network = "twitter",
                    ScreenName = accessToken["screen_name"],
                    AccessToken = accessToken["oauth_token"],
                    AccessTokenSecret = accessToken["oauth_token_secret"]
                });

            Events.Publish(Token);

            return Token;
        }
开发者ID:trainshare,项目名称:TrainShareApp,代码行数:42,代码来源:TwitterClient.cs

示例14: LoginAsync

        public async Task<Token> LoginAsync(WebBrowser browser)
        {
            // Check for network connectivity
            if (!NetworkInterface.GetIsNetworkAvailable()) return null;

            var guid = Guid.NewGuid().ToString();
            var client = new RestClient("https://www.facebook.com/dialog/oauth/");
            var request =
                new RestRequest()
                    .AddParameter("client_id", _consumerKey)
                    .AddParameter("redirect_uri", Redirect)
                    .AddParameter("scope", string.Empty)
                    .AddParameter("state", guid)
                    .AddParameter("response_type", "token");

            browser.IsScriptEnabled = true;

            var uri = client.BuildUri(request);
            var jsonToken = await GetRequestToken(browser, uri);

            if (jsonToken.ContainsKey("error_reason"))
                return null;
            if (jsonToken["state"] != guid)
                throw new SecurityException("Cross site forgery happend, the state did not equal the guid");

            var user = await GetUserInfo(jsonToken["access_token"]);

            InsertOrUpdateToken(
                new Token
                {
                    Id = user["id"].Value<int>(),
                    Network = "facebook",
                    ScreenName = user["name"].Value<string>(),
                    AccessToken = jsonToken["access_token"],
                    Expires = DateTime.Now + TimeSpan.FromSeconds(int.Parse(jsonToken["expires_in"]))
                });

            Events.Publish(Token);

            return Token;
        }
开发者ID:trainshare,项目名称:TrainShareApp,代码行数:41,代码来源:FacebookClient.cs

示例15: RequestAndAuthorize

        public ActionResult RequestAndAuthorize()
        {
            var baseUrl = "https://api.linkedin.com/uas/";
            var client = new RestClient(baseUrl);

            client.Authenticator = OAuth1Authenticator.ForRequestToken("abe1zbhwrjvc", "um8jHurIU5UPqURD", "http://localhost:4777/linkedin/oauthcallback");
            var request = new RestRequest("oauth/requestToken", Method.POST);

            var response = client.Execute(request);

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

            Session["oauth-secret"] = oauth_token_secret;

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

            return Redirect(url);

            //var credentials = new OAuthCredentials
            //{
            //    CallbackUrl = "http://127.0.0.1/oauth/callback/",
            //    ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
            //    ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
            //    Verifier = "123456",
            //    Type = OAuthType.RequestToken
            //};
            //var client = new RestClient { Authority = "https://api.linkedin.com/uas/oauth", Credentials = credentials };
            //var request = new RestRequest { Path = "requestToken" };
            //RestResponse response = client.Request(request);

            //string token = response.Content.Split('&amp;').Where(s =&gt; s.StartsWith("oauth_token=")).Single().Split('=')[1];
            //string token_secret = response.Content.Split('&amp;').Where(s =&gt; s.StartsWith("oauth_token_secret=")).Single().Split('=')[1];

            //Response.Redirect("https://api.linkedin.com/uas/oauth?oauth_token=" + token);
        }
开发者ID:karldennis,项目名称:LeadGen,代码行数:39,代码来源:LinkedInController.cs


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