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


C# HttpClient.Get方法代码示例

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


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

示例1: Should_get_a_messagge

        public void Should_get_a_messagge()
        {
            var contentType = "text/text";
            var payload = "Hello!";
            var message = new Message()
            {
                Id = Identity.Random(),
                TopicId = Identity.Random(),
                Payload = Encoding.ASCII.GetBytes(payload),
                UtcReceivedOn = DateTime.UtcNow
            };

            message.Headers.Add("Content-Type", new[] { contentType });

            var key = new MessageKey { MessageId = message.Id.Value, TopicId = message.TopicId };

            messageByMessageKey
                .Setup(r => r.Get(It.Is<MessageKey>(k => k.TopicId == key.TopicId && k.MessageId == key.MessageId)))
                .Returns(message);

            var client = new HttpClient(baseUri);
            var url = baseUri + message.Id.Value.ToString() + "/topic/" + message.TopicId;
            var result = client.Get(url);

            messageByMessageKey.Verify(r => r.Get(It.Is<MessageKey>(k => k.TopicId == key.TopicId && k.MessageId == key.MessageId)));

            Assert.IsNotNull(result);
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            Assert.AreEqual(payload, result.Content.ReadAsString());
            Assert.AreEqual(contentType, result.Content.Headers.ContentType.MediaType);
        }
开发者ID:ashic,项目名称:Hermes,代码行数:31,代码来源:MessageFixture.cs

示例2: Main

        static void Main(string[] args)
        {
            CookieContainer cookieContainer = new CookieContainer();
            using (HttpClient client = new HttpClient("http://localhost:44857/")) {
                HttpClientChannel clientChannel = new HttpClientChannel();
                clientChannel.CookieContainer = cookieContainer;
                client.Channel = clientChannel;
                HttpContent loginData = new FormUrlEncodedContent(
                    new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>("Username", "foo"),
                            new KeyValuePair<string, string>("Password", "bar")
                        }
                    );
                client.Post("login", loginData);
            }

            string result = string.Empty;
            using (HttpClient client = new HttpClient("http://localhost:44857/contact/")) {
                HttpClientChannel clientChannel = new HttpClientChannel();
                clientChannel.CookieContainer = cookieContainer;
                client.Channel = clientChannel;
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.Get("1");
                result = response.Content.ReadAsString();
            }

            JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer();
            ContactDto contact = jsonDeserializer.Deserialize<ContactDto>(result);
            Console.WriteLine(contact.Name);
            Console.ReadLine();
        }
开发者ID:AlexZeitler,项目名称:WcfHttpMvcFormsAuth,代码行数:32,代码来源:Program.cs

示例3: ValidateAccessToken

        public virtual bool ValidateAccessToken(string token)
        {
            if (!IsProviderEnabled())
                throw new ScrumFactory.Exceptions.AuthorizationProviderNotSupportedException();

            System.Net.Http.HttpClientHandler handler = new System.Net.Http.HttpClientHandler();
            handler.Proxy = System.Net.WebRequest.DefaultWebProxy;
            System.Net.Http.HttpClient wc = new System.Net.Http.HttpClient(handler);

            System.Net.Http.HttpResponseMessage msg = null;
            try {
                msg = wc.Get(new Uri(ValidateUrl + "?access_token=" + token));
            }
            catch (Exception ex) {
                throw new System.ServiceModel.Web.WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.BadRequest);
            }

            if (msg.StatusCode == HttpStatusCode.Unauthorized)
                return false;

            if (msg.StatusCode != HttpStatusCode.OK)
                throw new System.ServiceModel.Web.WebFaultException<string>("Server failed to validate token: " + msg.StatusCode.ToString(), System.Net.HttpStatusCode.BadRequest);

            dynamic info = msg.Content.ReadAs<JsonObject>();
            SetMemberInfo(info);
            return true;
        }
开发者ID:klot-git,项目名称:scrum-factory,代码行数:27,代码来源:OAuthBaseTokenValidator.cs

示例4: NextState

        public IApplicationState NextState(HttpClient client)
        {
            if (currentResponse.Content.Headers.ContentType.Equals(AtomMediaType.Feed))
            {
                var feed = currentResponse.Content.ReadAsObject<SyndicationFeed>(AtomMediaType.Formatter);
                if (feed.Categories.Contains(new SyndicationCategory("encounter"), CategoryComparer.Instance))
                {
                    return new ResolvingEncounter(currentResponse, applicationStateInfo);
                }
                return new Error(currentResponse, applicationStateInfo);
            }

            var entry = currentResponse.Content.ReadAsObject<SyndicationItem>(AtomMediaType.Formatter);

            if (entry.Title.Text.Equals("Exit"))
            {
                return new GoalAchieved(currentResponse);
            }

            var exitLink = GetExitLink(entry, applicationStateInfo.History, "north", "east", "west", "south");

            var newResponse = client.Get(new Uri(entry.BaseUri, exitLink.Uri));
            var exitUri = applicationStateInfo.History.Contains(exitLink.Uri) ? null : exitLink.Uri;

            return new Exploring(newResponse, applicationStateInfo.GetBuilder().AddToHistory(exitUri).Build());
        }
开发者ID:iansrobinson,项目名称:hydras-and-hypermedia,代码行数:26,代码来源:Exploring.cs

示例5: WhenOrdering_ThenSucceeds

	public void WhenOrdering_ThenSucceeds()
	{
		var config = HttpHostConfiguration.Create();
		config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

		using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", config))
		{
			var client = new HttpClient("http://localhost:20000");
			client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json"));

			var context = new DataServiceContext(new Uri("http://localhost:20000"));
			// We always specify how many to take, to be explicit.
			var query = context.CreateQuery<Product>("products")
				.Where(x => x.Owner.Name == "kzu")
				.OrderBy(x => x.Id)
				.ThenBy(x => x.Owner.Id)
				.Skip(1)
				.Take(1);

			//var uri = ((DataServiceQuery)query).RequestUri;
			var uri = new Uri(((DataServiceQuery)query).RequestUri.ToString().Replace("()?$", "?$"));
			Console.WriteLine(uri);
			var response = client.Get(uri);

			Assert.True(response.IsSuccessStatusCode, "Failed : " + response.StatusCode + " " + response.ReasonPhrase);

			var products = new JsonSerializer().Deserialize<List<Product>>(new JsonTextReader(new StreamReader(response.Content.ContentReadStream)));

			Assert.Equal(1, products.Count);
		}
	}
开发者ID:netfx,项目名称:extensions,代码行数:31,代码来源:HttpClientQuerySpec.cs

示例6: GetUnplannedSessions

 public IList<INosSession> GetUnplannedSessions()
 {
     using (HttpClient httpClient = new HttpClient(_baseAddress)) {
         httpClient.DefaultRequestHeaders.Accept.Add(_json);
         HttpResponseMessage response = httpClient.Get("sessions/unplanned");
         List<NosSession> sessions = response.Content.ReadAs<List<NosSession>>(new List<MediaTypeFormatter>() { new JsonMediaTypeFormatter() });
         return new List<INosSession>(sessions);
     }
 }
开发者ID:AlexZeitler,项目名称:OpenSpacePlanner,代码行数:9,代码来源:NosClient.cs

示例7: Index

        //
        // GET: /Home/
        public ActionResult Index()
        {
            HttpClient client = new HttpClient();// {BaseAddress = uri};
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = client.Get(uri);

            var donaldEpisodes = response.Content.ReadAs<List<DonaldEpisode>>();
            return View(donaldEpisodes);
        }
开发者ID:mastoj,项目名称:DonaldWCFwebApi,代码行数:11,代码来源:HomeController.cs

示例8: GetClaims

        public async Task<List<GetClaimsResponseItem>> GetClaims(string accessToken)
        {
            var client = new HttpClient()
            {
                BaseAddress = new Uri(_baseUri)
            };

            client.DefaultRequestHeaders.Authorization = JwtAuthHeader.GetHeader(accessToken);

            var response = await client.Get<List<GetClaimsResponseItem>>("values/claims");

            return response.Data;
        }
开发者ID:bjcull,项目名称:Pinch.SDK,代码行数:13,代码来源:AuthClient.cs

示例9: Validates_a_get_of_a_message_that_does_not_exist

        public void Validates_a_get_of_a_message_that_does_not_exist()
        {
            messageByMessageKey.Setup(s => s.Get(It.IsAny<MessageKey>())).Returns((Message)null);

            var client = new HttpClient(baseUri);
            var url = baseUri.ToString() + Identity.Random() + "/topic/" + Identity.Random();
            var result = client.Get(url);

            messageByMessageKey.Verify(r => r.Get(It.IsAny<MessageKey>()));

            Assert.IsNotNull(result);
            Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
        }
开发者ID:ashic,项目名称:Hermes,代码行数:13,代码来源:MessageFixture.cs

示例10: WhenGettingThenReturnsListOfPeopleAdded

 public void WhenGettingThenReturnsListOfPeopleAdded()
 {
     var peopleToSayHelloTo = new List<string>();
     peopleToSayHelloTo.Add("Glenn");
     HelloResource.Initialize(peopleToSayHelloTo);
     using (var host = new HttpServiceHost(typeof(HelloResource), this.hostUri))
     {
         host.Open();
         var client = new HttpClient();
         var response = client.Get(this.hostUri);
         Assert.AreEqual("Hello Glenn", response.Content.ReadAsString());
         host.Close();
     }
 }
开发者ID:nuxleus,项目名称:WCFWeb,代码行数:14,代码来源:HelloResourceAcceptanceTest.cs

示例11: basicAuthenticationSample

        private static void basicAuthenticationSample()
        {
            var client = new HttpClient(Urls.Code)
            {
                Channel = new BasicAuthenticationChannel(new WebRequestChannel(),
                                                         _ => Tuple.Create("test", "changeit"),
                                                         new WebRequestChannel())
            };

            var response = client.Get("preprompt/wcf/banzai.txt");
            response.EnsureSuccessStatusCode();
            Console.WriteLine(response);
            Console.WriteLine(response.Content.ReadAsString());
        }
开发者ID:prompt,项目名称:preprompt-wcf-http,代码行数:14,代码来源:Program.cs

示例12: LoadCodeReps

        public ICollection<string> LoadCodeReps(Project project)
        {
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client = new System.Net.Http.HttpClient();
            client.DefaultRequestHeaders.Add("user-agent", "SF-Client");

            var response = client.Get("https://api.github.com/user/repos?access_token=" + authorizator.SignedMemberToken);
            if(response.StatusCode!=System.Net.HttpStatusCode.OK)
                return new string[0];
            dynamic reposArray = response.Content.ReadAs<JsonArray>();
            List<string> repos = new List<string>();
            foreach (var repo in reposArray)
                repos.Add((string)repo.svn_url);
            return repos.ToArray();
        }
开发者ID:klot-git,项目名称:scrum-factory,代码行数:15,代码来源:GithubCodeRepositoryService.cs

示例13: Should_get_a_messagge_by_topic

        public void Should_get_a_messagge_by_topic()
        {
            var key = new MessageKey {MessageId = Identity.Random(), TopicId = Identity.Random()};

            messageKeysByTopic
                .Setup(r => r.Get(key.TopicId, null, null, null))
                .Returns(new[] {key});

            var client = new HttpClient(baseUri);
            var url = baseUri + "topic/" + key.TopicId;
            var result = client.Get(url);

            Assert.IsNotNull(result);
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
        }
开发者ID:ashic,项目名称:Hermes,代码行数:15,代码来源:MessagesFixture.cs

示例14: WhenHostingDisposableService_ThenDefaultActivatorFactoryDisposesIt

	public void WhenHostingDisposableService_ThenDefaultActivatorFactoryDisposesIt()
	{
		using (var webservice = new HttpWebService<TestService>(
			serviceBaseUrl: "http://localhost:20000",
			serviceResourcePath: "test",
			serviceConfiguration: HttpHostConfiguration.Create()))
		{
			var client = new HttpClient(webservice.BaseUri);

			// Builds: http://localhost:2000/test/23
			var uri = webservice.Uri("23");
			var response = client.Get(uri);
		}

		Assert.True(TestService.IsDisposed);
	}
开发者ID:netfx,项目名称:extensions,代码行数:16,代码来源:HttpWebServiceSpec.cs

示例15: ServiceHost_Works_With_OneWay_Operation

        public void ServiceHost_Works_With_OneWay_Operation()
        {
            ContractDescription cd = ContractDescription.GetContract(typeof(OneWayService));
            HttpServiceHost host = new HttpServiceHost(typeof(OneWayService), new Uri("http://localhost/onewayservice"));
            host.Open();

            using (HttpClient client = new HttpClient())
            {
                client.Channel = new WebRequestChannel();
                using (HttpResponseMessage actualResponse = client.Get("http://localhost/onewayservice/name"))
                {
                    Assert.AreEqual(actualResponse.StatusCode, HttpStatusCode.Accepted, "Response status code should be Accepted(202) for one-way operation");
                }
            }

            host.Close();
        }
开发者ID:nuxleus,项目名称:WCFWeb,代码行数:17,代码来源:HttpServiceHostTests.cs


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