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


C# HttpClient.GetAsync方法代码示例

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


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

示例1: Main

		static void Main(string[] args)
		{
			var tokenClient = new TokenClient(
				"http://localhost:18942/connect/token",
				"test",
				"secret");

			//This responds with the token for the "api" scope, based on the username/password above
			var response = tokenClient.RequestClientCredentialsAsync("api1").Result;

			//Test area to show api/values is protected
			//Should return that the request is unauthorized
			try
			{
				var unTokenedClient = new HttpClient();
				var unTokenedClientResponse = unTokenedClient.GetAsync("http://localhost:19806/api/values").Result;
				Console.WriteLine("Un-tokened response: {0}", unTokenedClientResponse.StatusCode);
			}
			catch (Exception ex)
			{
				Console.WriteLine("Exception of: {0} while calling api without token.", ex.Message);
			}


			//Now we make the same request with the token received by the auth service.
			var client = new HttpClient();
			client.SetBearerToken(response.AccessToken);

			var apiResponse = client.GetAsync("http://localhost:19806/identity").Result;
			var callApiResponse = client.GetAsync("http://localhost:19806/api/values").Result;
			Console.WriteLine("Tokened response: {0}", callApiResponse.StatusCode);
			Console.WriteLine(callApiResponse.Content.ReadAsStringAsync().Result);
			Console.Read();
		}
开发者ID:dkaminski,项目名称:IdentityServer3.Samples,代码行数:34,代码来源:Program.cs

示例2: Main

        static void Main()
        {
            var address = "http://localhost:9000/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();

                PrintResponse(client.GetAsync(address + "api/items.json").Result);
                PrintResponse(client.GetAsync(address + "api/items.xml").Result);

                PrintResponse(client.GetAsync(address + "api/items?format=json").Result);
                PrintResponse(client.GetAsync(address + "api/items?format=xml").Result);

                var message1 = new HttpRequestMessage(HttpMethod.Get, address + "api/items");
                message1.Headers.Add("ReturnType","json");
                var message2 = new HttpRequestMessage(HttpMethod.Get, address + "api/items");
                message2.Headers.Add("ReturnType", "xml");

                PrintResponse(client.SendAsync(message1).Result);
                PrintResponse(client.SendAsync(message2).Result);

                Console.ReadLine();
            }
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:25,代码来源:Program.cs

示例3: davisonConnectionTest

        public void davisonConnectionTest()
        {
            HttpClient davisonStore = new HttpClient();
            davisonStore.BaseAddress = new Uri("http://davisonstore.azurewebsites.net/");
            davisonStore.DefaultRequestHeaders.Accept.ParseAdd("application/json");

            HttpResponseMessage davisonResponse;

            var DavisonProducts = new List<TemporaryDavisonProductModel>().AsEnumerable();
            davisonResponse = davisonStore.GetAsync("api/Products").Result;
            if (davisonResponse.IsSuccessStatusCode)
            {
                DavisonProducts = davisonResponse.Content.ReadAsAsync<IEnumerable<TemporaryDavisonProductModel>>().Result;
            }

            Assert.IsNotNull(DavisonProducts);

            var DavisonCategories = new List<TemporaryDavisonCategoriesModel>().AsEnumerable();
            davisonResponse = davisonStore.GetAsync("api/Categories").Result;
            if (davisonResponse.IsSuccessStatusCode)
            {
                DavisonCategories = davisonResponse.Content.ReadAsAsync<IEnumerable<TemporaryDavisonCategoriesModel>>().Result;
            }

            Assert.IsNotNull(DavisonCategories);

            var DavisonBrands = new List<TemporaryDavisonBrandModel>().AsEnumerable();
            davisonResponse = davisonStore.GetAsync("api/Brands").Result;
            if (davisonResponse.IsSuccessStatusCode)
            {
                DavisonBrands = davisonResponse.Content.ReadAsAsync<IEnumerable<TemporaryDavisonBrandModel>>().Result;
            }

            Assert.IsNotNull(DavisonBrands);
        }
开发者ID:GasMaskManiac,项目名称:SuperSoftwareBros.,代码行数:35,代码来源:UnitTest1.cs

示例4: Index

        public async Task<ActionResult> Index()
        {
 
            var client = new HttpClient();
            
            // Vendas
            var response = await client.GetAsync("http://localhost:49990/api/Vendas/Total?ano=2015");
            var sales = await response.Content.ReadAsAsync<double>();
            
            // Funcionarios
            //response = await client.GetAsync("http://localhost:49990/api/Funcionarios");
            //var funcionarios = await response.Content.ReadAsAsync<IEnumerable<Funcionario>>();

            // Compras
            response = await client.GetAsync("http://localhost:49990/api/Compras/Total?ano=2015");
            var purchases = await response.Content.ReadAsAsync<double>();
            purchases = Math.Abs(purchases);

            // Dinheiro em caixa
            response = await client.GetAsync("http://localhost:49990/api/Compras/Cash");
            var cashMoney = await response.Content.ReadAsAsync<double>();

            // Valor do inventario
            response = await client.GetAsync("http://localhost:49990/api/Produtos/Value");
            var invValue = await response.Content.ReadAsAsync<double>();


            ViewBag.SalesValue = sales;
            ViewBag.PurchasesValue = purchases;
            //ViewBag.Funcionarios = funcionarios;
            ViewBag.Caixa = cashMoney;
            ViewBag.ValorInv = Math.Round(invValue);

            return View(sales);
        }
开发者ID:tiagommferreira,项目名称:360-dashboard,代码行数:35,代码来源:HomeController.cs

示例5: Body_WithSingletonControllerInstance_Fails

        public void Body_WithSingletonControllerInstance_Fails()
        {
            // Arrange
            HttpClient httpClient = new HttpClient();
            string baseAddress = "http://localhost";
            string requestUri = baseAddress + "/Test";
            HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration(baseAddress);
            configuration.Routes.MapHttpRoute("Default", "{controller}", new { controller = "Test" });
            configuration.ServiceResolver.SetService(typeof(IHttpControllerFactory), new MySingletonControllerFactory());
            HttpSelfHostServer host = new HttpSelfHostServer(configuration);
            host.OpenAsync().Wait();
            HttpResponseMessage response = null;

            try
            {
                // Act
                response = httpClient.GetAsync(requestUri).Result;
                response = httpClient.GetAsync(requestUri).Result;
                response = httpClient.GetAsync(requestUri).Result;

                // Assert
                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }

            host.CloseAsync().Wait();
        }
开发者ID:douchedetector,项目名称:mvc-razor,代码行数:33,代码来源:CustomControllerFactoryTest.cs

示例6: ReadText

        public void ReadText()
        {
            HttpClientHandler handler = new HttpClientHandler();


            HttpClient client = new HttpClient();

            var respContent = client.GetAsync("http://localhost/Greg.RestLearning.Service/RestFeedService1.svc/aaa/text").Result.Content;

            var task = client.GetAsync("http://localhost/Greg.RestLearning.Service/RestFeedService1.svc/aaa/text");

            // Asynchroniczne otrzymanie responsa
            task.ContinueWith(task1 =>
                {
                    
                    HttpResponseMessage response = task1.Result;

                    //sprawdzenie statusu zwrotnego otrzymanego w responsie...
                    response.EnsureSuccessStatusCode();


                    //odczytanie zawartosci odpowiedzi synchronicznie
                    var syncContent = response.Content.ReadAsStringAsync().Result;

                    var asyncContent = response.Content.ReadAsStringAsync();

                    Console.WriteLine(asyncContent.Result);
                });

            Console.WriteLine("Hit ENTER to exit...");

            Console.Read();

        }
开发者ID:syncgz,项目名称:Greg.RestLearning,代码行数:34,代码来源:HttpClientWrapper.cs

示例7: Extract

		/// <summary>
		/// SoundCloudのトラックをogg形式の音声ファイルとして抽出します
		/// </summary>
		/// <param name="listenPageUrl">視聴ページのURL</param>
		/// <returns>一時フォルダ上のファイルパス</returns>
		public override async Task<string> Extract(Uri listenPageUrl)
		{
			if (listenPageUrl == null)
				throw new ArgumentNullException("listenPageUrl");

			var clientId = "376f225bf427445fc4bfb6b99b72e0bf";
			// var clientId2 = "06e3e204bdd61a0a41d8eaab895cb7df";
			// var clientId3 = "02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea";

			var resolveUrl = "http://api.soundcloud.com/resolve.json?url={0}&client_id={1}";
			var trackStreamUrl = "http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}";

			using (var client = new HttpClient())
			{
				// get track id
				var res = await client.GetAsync(string.Format(resolveUrl, listenPageUrl, clientId));
				var resolveJsonString = await res.Content.ReadAsStringAsync();
				var resolveJson = DynamicJson.Parse(resolveJsonString);

				var trackId = (int)resolveJson.id;

				// get download url
				res = await client.GetAsync(string.Format(trackStreamUrl, trackId, clientId));
				var trackStreamJsonString = await res.Content.ReadAsStringAsync();
				var trackStreamJson = DynamicJson.Parse(trackStreamJsonString);

				string downloadUrl = trackStreamJson.http_mp3_128_url;

				return await Convert(downloadUrl, 0, false);
			}
		}
开发者ID:marihachi,项目名称:CrystalResonanceForDesktop,代码行数:36,代码来源:SoundCloudExtractor.cs

示例8: SiteContent

        public ActionResult SiteContent(string url)
        {
            HttpClient httpClient = new HttpClient();
            string htmlString = string.Empty;

            Run.TightLoop(5, () =>
            {
                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                if (!response.IsSuccessStatusCode) throw new ApplicationException("Could not connect");
                htmlString = response.Content.ReadAsStringAsync().Result;
            });

            Run.WithDefault(10, 2, () =>
            {
                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                if (!response.IsSuccessStatusCode) throw new ApplicationException("Could not connect");
                htmlString = response.Content.ReadAsStringAsync().Result;
            });

            Run.WithRandomInterval(10, 1, 5, () =>
            {
                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                if (!response.IsSuccessStatusCode) throw new ApplicationException("Could not connect");
                htmlString = response.Content.ReadAsStringAsync().Result;
            });

            Run.WithProgressBackOff(10, 1, 10, () =>
            {
                HttpResponseMessage response = httpClient.GetAsync(url).Result;
                if (!response.IsSuccessStatusCode) throw new ApplicationException("Could not connect");
                htmlString = response.Content.ReadAsStringAsync().Result;
            });

            return Json(htmlString, JsonRequestBehavior.AllowGet);
        }
开发者ID:vishipayyallore,项目名称:SampleWebApplication,代码行数:35,代码来源:CloudConceptsController.cs

示例9: Main

        static void Main(string[] args)
        {
            var address = "http://localhost:900";
            var config = new HttpSelfHostConfiguration(address);
            config.MapHttpAttributeRoutes();

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Server running at {0}. Press any key to exit", address);

                var client = new HttpClient() {BaseAddress = new Uri(address)};

                var persons = client.GetAsync("person").Result;
                Console.WriteLine(persons.Content.ReadAsStringAsync().Result);

                var newPerson = new Person {Id = 3, Name = "Luiz"};
                var response = client.PostAsJsonAsync("person", newPerson).Result;

                if (response.IsSuccessStatusCode)
                {
                    var person3 = client.GetAsync("person/3").Result;
                    Console.WriteLine(person3.Content.ReadAsStringAsync().Result);
                }

                Console.ReadLine();
            }

        }
开发者ID:amanarorasti,项目名称:dotnet,代码行数:29,代码来源:Program.cs

示例10: Main

    static void Main(string[] args)
    {
        Uri baseAddress = new Uri("http://ncs-sz-jinnan:3721");
        HttpClient httpClient = new HttpClient { BaseAddress = baseAddress };
        IEnumerable<Contact> contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
        Console.WriteLine("当前联系人列表");
        ListContacts(contacts);

        Contact contact = new Contact { Id = "003", Name = "王五", EmailAddress = "[email protected]", PhoneNo = "789" };
        Console.WriteLine("\n添加联系人003");
        httpClient.PutAsync<Contact>("/api/contacts", contact, new JsonMediaTypeFormatter()).Wait();
        contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;            
        ListContacts(contacts);

        contact = new Contact { Id = "003", Name = "王五", EmailAddress = "[email protected]", PhoneNo = "987" };
        Console.WriteLine("\n修改联系人003");
        httpClient.PostAsync<Contact>("/api/contacts", contact, new XmlMediaTypeFormatter()).Wait();
        contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
        ListContacts(contacts);

        Console.WriteLine("\n删除联系人003");
        httpClient.DeleteAsync("/api/contacts/003").Wait();
        contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
        ListContacts(contacts);

            
        Console.Read();
    }
开发者ID:xiaohong2015,项目名称:.NET,代码行数:28,代码来源:Program.cs

示例11: Main

        //static Uri _baseAddress = new Uri("https://" + Constants.WebHost + "/services/rest/");

        static void Main(string[] args)
        {
            while (true)
            {
                Helper.Timer(() =>
                    {
                        "Calling Service".ConsoleYellow();

                        var client = new HttpClient { BaseAddress = _baseAddress };
                        client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue("dominick", "dominick");

                        var response = client.GetAsync("identity").Result;
                        response.EnsureSuccessStatusCode();

                        var identity = response.Content.ReadAsAsync<ViewClaims>().Result;
                        identity.ForEach(c => Helper.ShowClaim(c));

                        // access anonymous method with authN
                        client.GetAsync("info").Result.Content.ReadAsStringAsync().Result.ConsoleGreen();
                        response.EnsureSuccessStatusCode();
                    });

                Console.ReadLine();
            }
        }
开发者ID:1nv4d3r5,项目名称:Thinktecture.IdentityModel.Web,代码行数:27,代码来源:Program.cs

示例12: InnerGetStationsAsync

        public override async Task<List<StationModelBase>> InnerGetStationsAsync()
        {
            using (var client = new HttpClient(new NativeMessageHandler()))
            {
                HttpResponseMessage response = await client.GetAsync(new Uri(string.Format(_tokenUrl + "?" + Guid.NewGuid().ToString()))).ConfigureAwait(false);
                var responseBodyAsText = await response.Content.ReadAsStringAsync();
                var pattern = @"(?<=ibikestation.asp\?)([^""]*)";
                if (Regex.IsMatch(responseBodyAsText, pattern))
                {
                    var regex = new Regex(pattern).Match(responseBodyAsText);
                    if (regex != null && regex.Captures.Count > 0)
                    {
                        var id = regex.Captures[0].Value;

                        response = await client.GetAsync(new Uri(string.Format("{0}?{1}", StationsUrl, id)));
                        responseBodyAsText = await response.Content.ReadAsStringAsync();

                        pattern = @"(\[.*[\s\S]*?])";
                        if (Regex.IsMatch(responseBodyAsText, pattern))
                        {
                            regex = new Regex(pattern).Match(responseBodyAsText);
                            if (regex != null && regex.Captures.Count > 0)
                            {
                                return JsonConvert.DeserializeObject<List<PublicBicycleModel>>(regex.Captures[0].Value).Cast<StationModelBase>().ToList();
                            }
                        }
                    }
                }
            }
            return null;
        }
开发者ID:ThePublicBikeGang,项目名称:EasyBike,代码行数:31,代码来源:DangtuContract.cs

示例13: Create

 public static Ec2MetaData Create(string url = "http://169.254.169.254/latest/meta-data/")
 {
     var result = new Ec2MetaData();
     var client = new HttpClient();
     try
     {
         Task.WaitAll(
             client.GetAsync(url + "ami-id").ContinueWith(task =>
             {
                 if (task.IsCompleted)
                     result.AmiId = task.Result.Content.ReadAsStringAsync().Result;
             }),
             client.GetAsync(url + "hostname").ContinueWith(task =>
             {
                 if (task.IsCompleted)
                     result.Hostname = task.Result.Content.ReadAsStringAsync().Result;
             }),
             client.GetAsync(url + "instance-id").ContinueWith(task =>
             {
                 if (task.IsCompleted)
                     result.InstanceId = task.Result.Content.ReadAsStringAsync().Result;
             }),
             client.GetAsync(url + "instance-type").ContinueWith(task =>
             {
                 if (task.IsCompleted)
                     result.InstanceType = task.Result.Content.ReadAsStringAsync().Result;
             })
             );
     }
     catch (Exception exception)
     {
         Log.Error(exception, "Oops");
     }
     return result;
 }
开发者ID:tvjames,项目名称:apphb-play-console,代码行数:35,代码来源:Ec2MetaData.cs

示例14: LogOnAsync

        // <snippet508>
        public async Task<LogOnResult> LogOnAsync(string userId, string password)
        {
            using (var handler = new HttpClientHandler { CookieContainer = new CookieContainer() })
            {
                using (var client = new HttpClient(handler))
                {
                    client.AddCurrentCultureHeader();
                    // Ask the server for a password challenge string
                    var requestId = GenerateRequestId();
                    var response1 = await client.GetAsync(_clientBaseUrl + "GetPasswordChallenge?requestId=" + requestId);
                    response1.EnsureSuccessStatusCode();
                    var challengeEncoded = await response1.Content.ReadAsAsync<string>();
                    var challengeBuffer = CryptographicBuffer.DecodeFromHexString(challengeEncoded);

                    // Use HMAC_SHA512 hash to encode the challenge string using the password being authenticated as the key.
                    var provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha512);
                    var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
                    var hmacKey = provider.CreateKey(passwordBuffer);
                    var buffHmac = CryptographicEngine.Sign(hmacKey, challengeBuffer);
                    var hmacString = CryptographicBuffer.EncodeToHexString(buffHmac);

                    // Send the encoded challenge to the server for authentication (to avoid sending the password itself)
                    var response = await client.GetAsync(_clientBaseUrl + userId + "?requestID=" + requestId +"&passwordHash=" + hmacString);

                    // Raise exception if sign in failed
                    response.EnsureSuccessStatusCode();

                    // On success, return sign in results from the server response packet
                    var result = await response.Content.ReadAsAsync<UserInfo>();
                    var serverUri = new Uri(Constants.ServerAddress);
                    return new LogOnResult { ServerCookieHeader = handler.CookieContainer.GetCookieHeader(serverUri), UserInfo = result };
                }
            }
        }
开发者ID:stevenh77,项目名称:ItineraryHunter-Win8,代码行数:35,代码来源:IdentityServiceProxy.cs

示例15: Main

        static void Main(string[] args)
        {
            System.Threading.Thread.Sleep(100);
            Console.Clear();

            Console.WriteLine("**************************开始执行获取API***********************************");
            HttpClient client = new HttpClient();

            //Get All Product 获取所有
            HttpResponseMessage responseGetAll = client.GetAsync(url + "api/Products").Result;
            string GetAllProducts = responseGetAll.Content.ReadAsStringAsync().Result;
            Console.WriteLine("GetAllProducts方法:" + GetAllProducts);

            //Get Product根据ID获取
            HttpResponseMessage responseGetID = client.GetAsync(url + "api/Products/1").Result;
            string GetProduct = responseGetID.Content.ReadAsStringAsync().Result;
            Console.WriteLine("GetProduct方法:" + GetProduct);

            //Delete Product 根据ID删除
            HttpResponseMessage responseDeleteID = client.DeleteAsync(url + "api/Products/1").Result;
            // string DeleteProduct = responseDeleteID.Content.ReadAsStringAsync().Result;
            Console.WriteLine("DeleteProduct方法:" );

            //HttpContent abstract 类

            //Post  Product 添加Product对象
            var model = new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M };
            HttpContent content = new ObjectContent(typeof(Product), model, new JsonMediaTypeFormatter());
            client.PostAsync(url + "api/Products/", content);

            //Put Product  修改Product
            client.PutAsync(url + "api/Products/", content);

            Console.ReadKey();
        }
开发者ID:gudicao,项目名称:WebApiStu,代码行数:35,代码来源:Program.cs


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