GetAsync() public method

public GetAsync ( Uri requestUri ) : Task
requestUri System.Uri
return Task
Example #1
1
        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();
            }
        }
        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();
        }
Example #3
0
    static void Main(string[] args)
    {
        Uri baseAddress = new Uri("http://*****:*****@gmail.com", 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 = "*****@*****.**", 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();
    }
Example #4
0
        public void Static_ValidIfModifiedSince(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, ValidModifiedSinceConfiguration);
                var httpClient = new HttpClient() { BaseAddress = new Uri(applicationUrl) };
                var fileContent = File.ReadAllBytes(@"RequirementFiles/Dir1/RangeRequest.txt");

                var response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);

                //Modified since = lastmodified. Expect a 304
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified;
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.NotModified, response.StatusCode);

                //Modified since > lastmodified. Expect a 304
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified.Value.AddMinutes(12);
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.NotModified, response.StatusCode);

                //Modified since < lastmodified. Expect an OK. 
                httpClient.DefaultRequestHeaders.IfModifiedSince = response.Content.Headers.LastModified.Value.Subtract(new TimeSpan(10 * 1000));
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
                CompareBytes(fileContent, response.Content.ReadAsByteArrayAsync().Result, 0, fileContent.Length - 1);

                //Modified since is an invalid date string. Expect an OK. 
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("If-Modified-Since", "InvalidDate");
                response = httpClient.GetAsync(@"RequirementFiles/Dir1/RangeRequest.txt").Result;
                Assert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
            }
        }
        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();

        }
Example #6
0
        protected async void Reload()
        {
            int idRest = Convert.ToInt16(Session["idRest"]);

            HttpClient httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(ip);

            //mesas desse restaurante
            var response = await httpClient.GetAsync("/20131011110061/api/mesa");
            var str = response.Content.ReadAsStringAsync().Result;
            List<Models.Mesa> obj = JsonConvert.DeserializeObject<List<Models.Mesa>>(str);
            List<Models.Mesa> listamesas = (from Models.Mesa c in obj where c.Restaurante_id == idRest && c.Disponivel == false select c).ToList();

            var response2 = await httpClient.GetAsync("/20131011110061/api/pedido");
            var str2 = response2.Content.ReadAsStringAsync().Result;
            List<Models.Pedido> ped = JsonConvert.DeserializeObject<List<Models.Pedido>>(str2);

            var result = from Models.Pedido pedido in ped
                         join Models.Mesa mesa in listamesas
                         on pedido.Mesa_Id equals mesa.Id
                         select mesa.comPedido(pedido);

            GridView1.DataSource = result.ToList();
            GridView1.DataBind();
        }
Example #7
0
        static void Main(string[] args)
        {
            var localClient = new HttpClient();
            localClient.BaseAddress = new Uri("https://windows8vm/ngmd/api/");
            localClient.SetBasicAuthentication("cw", "cw");

            var cloudClient = new HttpClient();
            cloudClient.BaseAddress = new Uri("https://demo.christianweyer.net/api/");
            cloudClient.SetBasicAuthentication("cw", "cw");

            while (true)
            {
                Console.WriteLine("Calling 'personalization'");
                localClient.GetAsync("personalization");
                cloudClient.GetAsync("personalization");
                Console.WriteLine("Calling 'articles'");
                localClient.GetAsync("articles");
                cloudClient.GetAsync("articles");
                Console.WriteLine("Calling 'images'");
                localClient.GetAsync("images");
                cloudClient.GetAsync("images");
                Console.WriteLine("Calling 'statistics'");
                localClient.GetAsync("statistics");
                cloudClient.GetAsync("statistics");

                Thread.Sleep(10000);
            }
        }
		/// <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);
			}
		}
Example #9
0
        private void GetRequest(string getParams)
        {
            bool done = false;
            int retries = 0;
            while (done == false)
            {
                try
                {
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(string.Format("http://{0}", SwitchIp));
                        client.Timeout = new TimeSpan(0, 0, 5);
                        client.GetAsync("report").Wait();
                        client.GetAsync(getParams).Wait();
                        done = true;
                    }
                }
                catch (Exception)
                {
                    if (retries == 3)
                        throw;

                    retries++;
                }
            }
        }
		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();
		}
        private static async Task GetPeople(string address)
        {
            var uriBuilder = new UriBuilder(address);
            uriBuilder.Path = "api/Customer";

            using (var client = new HttpClient())
            {
                Console.WriteLine("Getting data without a version...");
                var response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();

                Console.WriteLine("Getting data for v1...");
                client.DefaultRequestHeaders.Add("api-version", "1");
                response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();


                Console.WriteLine("Getting data for v2...");
                client.DefaultRequestHeaders.Remove("api-version");
                client.DefaultRequestHeaders.Add("api-version", "2");
                response = await client.GetAsync(uriBuilder.Uri);
                response.EnsureSuccessStatusCode();

                Console.WriteLine(await response.Content.ReadAsStringAsync());
                Console.WriteLine();
            }
        }
Example #12
0
        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();
            }

        }
        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);
        }
        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;
        }
Example #15
0
 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;
 }
 public async Task Blink() {
     using (HttpClient client = new HttpClient()) {
         await client.GetAsync("http://192.168.10.253/cgi-bin/relay.cgi?on");
         await Task.Delay(2000);
         await client.GetAsync("http://192.168.10.253/cgi-bin/relay.cgi?off");
     }
 }
        /// <summary>
        /// Loads the profile data for all users from the steam service
        /// </summary>
        /// <returns>The async task context.</returns>
        public async Task LoadSteamAsync(string apiKey)
        {
            var builder = new StringBuilder();
            for (var i = 0; i < Players.Count; i++)
                builder.Append(Players[i].SteamId + ",");

            using (var client = new HttpClient())
            {
                client.BaseAddress = new System.Uri("https://api.steampowered.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var response = await client.GetAsync(string.Format("ISteamUser/GetPlayerSummaries/v0002/?key={0}&steamids={1}", apiKey, builder.ToString()));
                if (response.IsSuccessStatusCode)
                    using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        LinkSteamProfiles(await reader.ReadToEndAsync());
                    }
                else
                    throw new System.Exception("The Steam API request was unsuccessful. Are you using a valid key?");

                response = await client.GetAsync(string.Format("ISteamUser/GetPlayerBans/v1/?key={0}&steamids={1}", apiKey, builder.ToString()));
                if (response.IsSuccessStatusCode)
                    using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        LinkSteamBans(await reader.ReadToEndAsync());
                    }
                else
                    throw new System.Exception("The Steam API request was unsuccessful. Are you using a valid key?");
            }
            SteamLoaded = true;
        }
Example #18
0
        public async void Reload()
        {
            int idRest = Convert.ToInt16(Session["idRest"]);

            HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri(ip);

            var response2 = await httpClient.GetAsync("/20131011110061/api/restaurante");
            var str2 = response2.Content.ReadAsStringAsync().Result;
            List<Models.Restaurante> obj2 = JsonConvert.DeserializeObject<List<Models.Restaurante>>(str2);

            var response = await httpClient.GetAsync("/20131011110061/api/cardapio");
            var str = response.Content.ReadAsStringAsync().Result;
            List<Models.Cardapio> obj = JsonConvert.DeserializeObject<List<Models.Cardapio>>(str);

            List<Models.Cardapio> obj3 = new List<Models.Cardapio>();
            
            /*foreach (Models.Cardapio x in obj)
            {
                if (x.Restaurante_id == idRest)
                {
                    obj3.Add(x);
                }
            }*/

            obj3 = (from Models.Cardapio c in obj where c.Restaurante_id == idRest orderby c.Descricao select c).ToList();

            GridView1.DataSource = obj3;
            GridView1.DataBind();
        }
        public async Task<IEnumerable<BeerModel>> GetBeers()
        {
            HttpClient client = new HttpClient();
            
            HttpResponseMessage response = await client.GetAsync(rootUrl + "/api/beer/");
            IEnumerable<BeerModel> beers = await response.Content.ReadAsAsync<IEnumerable<BeerModel>>();

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/png"));

            foreach (BeerModel beer in beers)
            {
                response = await client.GetAsync(rootUrl + "/api/beer/" + beer.Id);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    byte[] data = await response.Content.ReadAsByteArrayAsync();

                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.StreamSource = new MemoryStream(data);
                    image.EndInit();

                    beer.Image = image;
                }
            }

            return beers;
        }
        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);
        }
Example #21
0
        protected async void btnSelect_Click(object sender, EventArgs e)
        {
            HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri(ip);

            var response2 = await httpClient.GetAsync("/20131011110061/api/usuariosistema");
            var str2 = response2.Content.ReadAsStringAsync().Result;
            List<Models.UsuarioSistema> obj2 = JsonConvert.DeserializeObject<List<Models.UsuarioSistema>>(str2);

            var obj = (from Models.UsuarioSistema r in obj2 where r.Restaurante_id == int.Parse(RestaurantesSelect.SelectedValue) orderby r.Usuario select r).ToList();

            var response3 = await httpClient.GetAsync("/20131011110061/api/restaurante");
            var str3 = response3.Content.ReadAsStringAsync().Result;
            List<Models.Restaurante> obj3 = JsonConvert.DeserializeObject<List<Models.Restaurante>>(str3);

            var result = from Models.UsuarioSistema us in obj
                         join Models.Restaurante p in obj3
                         on us.Restaurante_id equals p.Id
                         select us.ComRestaurante(p);

            GridView1.DataSource = result.ToList();
            GridView1.DataBind();
            DropRest();
        }
Example #22
0
        static async Task RunAsync() {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:53402/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // New code:
                HttpResponseMessage response = await client.GetAsync("Home/Get/1");
                if (response.IsSuccessStatusCode)
                {
                    var vm = await response.Content.ReadAsAsync<SameViewModelButDifferentName>();
                    Console.WriteLine("{0}|{1}|{2}", vm.Name, vm.State, vm.Url);
                }

                response = await client.GetAsync("Home/Get/2");
                if (response.IsSuccessStatusCode)
                {
                    var vm = await response.Content.ReadAsAsync<SameViewModelButDifferentName>();
                    Console.WriteLine("{0}|{1}|{2}", vm.Name, vm.State, vm.Url);
                }

                response = await client.GetAsync("Home/Get/3");
                if (response.IsSuccessStatusCode)
                {
                    var vm = await response.Content.ReadAsAsync<SameViewModelButDifferentName>();
                    Console.WriteLine("{0}|{1}|{2}", vm.Name, vm.State, vm.Url);
                }
            }
        }
        public void SetUp()
        {
            var fakeResponseDelegatingHandler = new FakeResponseDelegatingHandler();

            fakeResponseDelegatingHandler.AddFakeResponse(new Uri(TEST_URI), () => new HttpResponseMessage(HttpStatusCode.InternalServerError));
            fakeResponseDelegatingHandler.AddFakeResponse(new Uri(TEST_URI), () => new HttpResponseMessage(HttpStatusCode.InternalServerError));
            fakeResponseDelegatingHandler.AddFakeResponse(new Uri(TEST_URI), () => new HttpResponseMessage(HttpStatusCode.OK));

            httpClient = new HttpClient(new CircuitBreakingDelegatingHandler(EXCEPTIONS_ALLOWED_BEFORE_BREAKING, circuitOpenDuration, fakeResponseDelegatingHandler));

            // trigger circuit break
            response1 = httpClient.GetAsync(TEST_URI).Result;
            response2 = httpClient.GetAsync(TEST_URI).Result;

            // circuit should be open
            try
            {
                var response3 = httpClient.GetAsync(TEST_URI).Result;
            }
            catch (BrokenCircuitException brokenCircuitException)
            {
                httpClientException = brokenCircuitException;
            }

            WaitCircuitToBeClosed();

            response4 = httpClient.GetAsync(TEST_URI).Result;
        }
        public void cache_singleton_in_pipeline()
        {
            _cache = new Mock<IApiOutputCache>();

            var conf = new HttpConfiguration();
            conf.CacheOutputConfiguration().RegisterCacheOutputProvider(() => _cache.Object);

            conf.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            _server = new HttpServer(conf);

            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_c100_s100").Result;

            _cache.Verify(s => s.Contains(It.Is<string>(x => x == "webapi.outputcache.v2.tests.testcontrollers.samplecontroller-get_c100_s100:application/json; charset=utf-8")), Times.Exactly(2));

            var result2 = client.GetAsync(_url + "Get_c100_s100").Result;
            _cache.Verify(s => s.Contains(It.Is<string>(x => x == "webapi.outputcache.v2.tests.testcontrollers.samplecontroller-get_c100_s100:application/json; charset=utf-8")), Times.Exactly(4));

            _server.Dispose();
        }
        // <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 };
                }
            }
        }
        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);
        }
        //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();
            }
        }
        public static string DoGet(string url)
        {
            var handler = new HttpClientHandler {
                AutomaticDecompression = DecompressionMethods.GZip
            };

            using (var http = new System.Net.Http.HttpClient(handler))
            {
                //await异步等待回应
                var response = http.GetAsync(url).Result;
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                return(response.Content.ReadAsStringAsync().Result);
            }
        }
Example #29
0
        /// <summary>
        /// Sends the GET request to the given URI.
        /// </summary>
        /// <param name="httpClient"><see cref="System.Net.Http.HttpClient"/> instance.</param>
        /// <param name="requestUri">Request URI.</param>
        /// <param name="validator"><see cref="ISchemaValidator"/> instance.</param>
        /// <param name="path">Schema path.</param>
        /// <param name="cancellationToken"><see cref="CancellationToken"/> instance.</param>
        /// <returns>Returns <see cref="HttpResponseMessage"/> instance.</returns>
        public static async Task <HttpResponseMessage> GetAsync(this System.Net.Http.HttpClient httpClient, Uri requestUri, ISchemaValidator validator, string path, CancellationToken cancellationToken)
        {
            httpClient.ThrowIfNullOrDefault();
            requestUri.ThrowIfNullOrDefault();
            validator.ThrowIfNullOrDefault();
            path.ThrowIfNullOrWhiteSpace();
            cancellationToken.ThrowIfNullOrDefault();

            var response = await httpClient.GetAsync(requestUri, cancellationToken).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();

            await ValidateAsync(response, validator, path).ConfigureAwait(false);

            return(response);
        }
Example #30
0
        public static List <ProductDTO> GetListProduct()
        {
            List <ProductDTO> result;
            const string      url = "http://localhost/ConsumingAPI/api/Products ";

            using (var client = new System.Net.Http.HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.GetAsync(url).Result;
                var data     = response.Content.ReadAsStringAsync().Result;
                result = JsonConvert.DeserializeObject <List <ProductDTO> >(data);
            }
            return(result);
        }
Example #31
0
        // GET: gider/Create
        public async System.Threading.Tasks.Task <ActionResult> CreateAsync()
        {
            List <HarcamaTuru>      haracamaTurleri = new List <HarcamaTuru>();
            List <harcamaTuruModel> modelData       = new List <harcamaTuruModel>();

            try
            {
                // Create a HttpClient
                using (var client = new System.Net.Http.HttpClient())
                {
                    // Setup basics
                    client.BaseAddress = new Uri("http://localhost:49774/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // Get Request from the URI
                    using (var result = await client.GetAsync("api/HarcamaTuru"))
                    {
                        // Check the Result
                        if (result.IsSuccessStatusCode)
                        {
                            // Take the Result as a json string
                            var value = result.Content.ReadAsStringAsync().Result;

                            // Deserialize the string with a Json Converter to ResponseContent object and fill the datagrid
                            haracamaTurleri = JsonConvert.DeserializeObject <ResponseContent <HarcamaTuru> >(value).Data.ToList();
                        }
                    }
                }
                foreach (var item in haracamaTurleri)
                {
                    harcamaTuruModel yeniHarcama = new harcamaTuruModel
                    {
                        harcamaTuru = item.harcamaTuru,
                        harcamaId   = item.harcamaId,
                    };
                    modelData.Add(yeniHarcama);
                }

                return(View(modelData));
            }
            catch (Exception ex)
            {
                return(View());
            }
            return(View());
        }
        public async Task <ActionResult> Image(string key)
        {
            var post = key != null ? await Repository.GetPostAsync(key) : null;

            if (post == null)
            {
                return(await SearchNotFound());
            }

            if (NotModifiedSince(post.Timestamp))
            {
                return(StatusCode(StatusCodes.Status304NotModified));
            }

            var thumbnailUri = post.GetThumbnailUri();

            var thumbnailUriProxy = thumbnailUri.ToProxyUrl();

            var client = new System.Net.Http.HttpClient(new HttpClientHandler()
            {
                UseDefaultCredentials = true
            });

            client.DefaultRequestHeaders.Referrer = new Uri(string.Concat(Request.Scheme, "://", Request.Host.ToUriComponent(), Request.PathBase.ToUriComponent(), Request.Path, Request.QueryString));

            //Originally tried to get the stream directly using the httpclient as per below, but from the stream there is no way to
            //accurately tell the content type. Which is needed in order to send the stream correctly.

            //var stream = await client.GetStreamAsync(thumbnailUriProxy);

            //Instead we simply get the HTTP Request Response
            var result = await client.GetAsync(thumbnailUriProxy);

            //Get the type from the response as interpreted by the proxy server
            var type = result.Content.Headers.ContentType;

            //Then create the stream based on the response content.
            var stream = await result.Content.ReadAsStreamAsync();

            if (stream == null)
            {
                return(await SearchNotFound());
            }

            return(File(stream, type.ToString()));
        }
Example #33
0
        public async Task SimpleGetWithDefaultHeader()
        {
            var client = new System.Net.Http.HttpClient();

            client.BaseAddress = new Uri("https://en.wikipedia.org/w/api.php");

            var userAgentHeaderValue = new ProductInfoHeaderValue("DemoTool", "1.0");

            client.DefaultRequestHeaders.UserAgent.Add(userAgentHeaderValue);

            var response = await client.GetAsync("?action=query&prop=info&titles=Main%20Page&format=json");

            Assert.Equal(200, (int)response.StatusCode);
            var result = await response.Content.ReadAsStringAsync();

            _testOutputHelper.WriteLine($"Text: {result}");
        }
Example #34
0
        private async Task WaitForNextUpdates()
        {
            using (var httpClient = new HttpClient())
            {
                string uri = $"{BaseUri}{AuthenticationToken}/getUpdates?timeout=60&offset={_latestUpdateId + 1}";
                HttpResponseMessage response = await httpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    throw new InvalidOperationException($"Failed to fetch new updates of TelegramBot (StatusCode={response.StatusCode}).");
                }

                string body = await response.Content.ReadAsStringAsync();

                ProcessUpdates(body);
            }
        }
Example #35
0
        public static async Task <T> GetAsync <T>(this System.Net.Http.HttpClient client, string uri)
        {
            var response = await client.GetAsync(uri);

            if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return(default(T));
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new HttpRequestException(await response.Content.ReadAsStringAsync());
            }
            response.EnsureSuccessStatusCode();
            var result = await response.Content.ReadAsync <T>();

            return(result);
        }
Example #36
0
        private async void LoadMapButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string uri = string.Format("http://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?supressStatus=true&key={0}", BingKeyTextBox.Text);

                HttpClient          http     = new System.Net.Http.HttpClient();
                HttpResponseMessage response = await http.GetAsync(uri);

                var bingAuthStream = await response.Content.ReadAsStreamAsync();

                DataContractJsonSerializer serializer         = new DataContractJsonSerializer(typeof(BingAuthentication));
                BingAuthentication         bingAuthentication = serializer.ReadObject(bingAuthStream) as BingAuthentication;
                string authenticationResult = bingAuthentication.AuthenticationResultCode.ToString();
                if (authenticationResult == "ValidCredentials")
                {
                    foreach (BingLayer.LayerType layerType in (BingLayer.LayerType[])Enum.GetValues(typeof(BingLayer.LayerType)))
                    {
                        BingLayer bingLayer = new BingLayer()
                        {
                            ID        = layerType.ToString(),
                            MapStyle  = layerType,
                            Key       = BingKeyTextBox.Text,
                            IsVisible = false
                        };

                        MyMap.Layers.Add(bingLayer);
                    }

                    MyMap.Layers[0].IsVisible = true;

                    BingKeyGrid.Visibility             = Visibility.Collapsed;
                    InvalidBingKeyTextBlock.Visibility = Visibility.Collapsed;
                    LayerStyleGrid.Visibility          = Visibility.Visible;
                }
                else
                {
                    InvalidBingKeyTextBlock.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                InvalidBingKeyTextBlock.Visibility = Visibility.Visible;
            }
        }
        // GET: DeliveryMen
        public ActionResult Index()
        {
            var response = httpClient.GetAsync(baseAddress + "ConsomiTounsi/Delivery/DeliveryMens").Result;

            if (response.IsSuccessStatusCode)
            {
                var dm = response.Content.ReadAsAsync <IEnumerable <DeliveryMen> >().Result;
                return(View(dm));
            }
            else
            {
                Console.WriteLine("Internal server Error");
                return(View(new List <DeliveryMen>()));
            }
        }
Example #38
0
        public async Task <string> GetData(string url)
        {
            string responseBody = null;

            var uri = new Uri(url);

            System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();

            System.Net.Http.HttpResponseMessage response = await httpClient.GetAsync(uri);

            if (response.IsSuccessStatusCode)
            {
                responseBody = response.Content.ReadAsStringAsync().Result;
            }

            return(responseBody);
        }
Example #39
0
        private HttpResponseMessage GET(string url)
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                try
                {
                    var result = client.GetAsync(url);
                    result.Wait();

                    return(result.Result);
                }
                catch (AggregateException)
                {
                    return(new HttpResponseMessage(System.Net.HttpStatusCode.ServiceUnavailable));
                }
            }
        }
Example #40
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <param name="downloading"></param>
        public static void Download(string url, string path, DownloadingDelegate downloading = null)
        {
            // 新建一个Handler
            var handler = new HttpClientHandler {
                AutomaticDecompression = DecompressionMethods.None,
                AllowAutoRedirect      = true,
                UseProxy = false,
                Proxy    = null,
                ClientCertificateOptions = ClientCertificateOption.Automatic
            };

            // 新建一个HttpClient
            var webRequest = new System.Net.Http.HttpClient(handler);
            HttpResponseMessage response = webRequest.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result;

            // 创建文件操作流
            using (FileStream fs = System.IO.File.Open(path, FileMode.Create)) {
                var  task          = response.Content.CopyToAsync(fs);
                var  contentLength = response.Content.Headers.ContentLength.GetValueOrDefault();
                bool isDone        = false;

                // 判断是否需要进行回调
                if (downloading != null)
                {
                    new Task(() => {
                        while (!task.IsCompleted)
                        {
                            downloading(contentLength, fs.Length);
                            if (fs.Length >= contentLength && contentLength > 0)
                            {
                                isDone = true;
                            }
                            System.Threading.Thread.Sleep(500);
                        }
                    }).Start();
                }

                task.Wait();

                // 判断是否需要再回调一次进度更新
                if (downloading != null && contentLength > 0 && !isDone)
                {
                    downloading(contentLength, fs.Length);
                }
            }
        }
        public KnowledgeBaseDetails GetDetails()
        {
            if (null != this.details)
            {
                return(this.details);
            }

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                string RequestURI = $"https://{this.azureServicName}.{baseUrl}/qnamaker/v4.0/knowledgebases/";

                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ocpApimSubscriptionKey);

                System.Net.Http.HttpResponseMessage msg = client.GetAsync(RequestURI).Result;

                msg.EnsureSuccessStatusCode();

                var JsonDataResponse = msg.Content.ReadAsStringAsync().Result;

                KnowledgeBaseListAllRootObject allKBs = JsonConvert.DeserializeObject <KnowledgeBaseListAllRootObject>(JsonDataResponse);

                if (null == allKBs)
                {
                    throw new JsonException("Could not deserialize the list of knowledgebases");
                }

                if (!string.IsNullOrEmpty(this.knowledgeBaseId))
                {
                    this.details = allKBs.knowledgebases.FirstOrDefault(p => p.id == this.knowledgeBaseId);
                    return(this.details);
                }

                var allDetails = allKBs.knowledgebases.Where(p => p.name == this.knowledgebase).ToArray();
                if (allDetails.Length == 0)
                {
                    return(null);
                }
                if (allDetails.Length > 1)
                {
                    throw new KeyNotFoundException($"More than one Knowledge base found with name {this.knowledgebase}, please pass in knowledge base id to differentiate them");
                }

                this.details = allDetails[0];
                return(this.details);
            }
        }
Example #42
0
        public async void GetData()
        {
            //HttpClient client = new HttpClient();
            var client   = new System.Net.Http.HttpClient();
            var response = await client.GetAsync("http://demo7712681.mockable.io/workout");

            string JsonData = await response.Content.ReadAsStringAsync();

            WorkoutLists ObjWorkoutList = new WorkoutLists();


            if (JsonData != "null")
            {
                ObjWorkoutList = JsonConvert.DeserializeObject <WorkoutLists>(JsonData);
            }
            WorkoutListView.ItemsSource = ObjWorkoutList.workouts;
        }
Example #43
0
        // GET api/values/5
        public string Get(string id)
        {
            if (id == "3")
            {
                Quix.Auth auth = new Quix.Auth(
                    System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString(),
                    System.Configuration.ConfigurationManager.AppSettings["TenantId"].ToString(),
                    System.Configuration.ConfigurationManager.AppSettings["TenantUrl"].ToString(),
                    System.Configuration.ConfigurationManager.AppSettings["AccessScopes"].ToString().Split(','),
                    System.Configuration.ConfigurationManager.AppSettings["TokenFile"].ToString());

                System.Net.Http.HttpClient          client   = auth.GetHttpClient();
                System.Net.Http.HttpResponseMessage response = client.GetAsync("https://cjvandyk.sharepoint.com/sites/Approval/_api/web/lists/GetByTitle('Approval')/items?$select=Title,ID&$filter=Title%20eq%20%27Test%27").GetAwaiter().GetResult();
                return("value {" + id + "}" + response.ToString());
            }
            return("value {" + (Convert.ToInt16(id) + 27) + "}");
        }
Example #44
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                /*
                 * using (WebClient client = new WebClient())
                 * {
                 *  client.Headers.Add("user-agent", "Mozilla / 5.0(Windows NT 10.0; WOW64; Trident / 7.0; rv: 11.0) like Gecko");
                 *  client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                 *  client.Headers.Add("Authorization", "SNAeoB88JTmAXfNTAfpR");
                 *
                 *  string response = "";
                 *  try
                 *  {
                 *
                 *      response = client.DownloadString("https://sandbox.apply-for-teacher-training.service.gov.uk/api/v1/applications?since=2018-10-01T10:00:00Z");
                 *  }
                 *  catch (Exception e2)
                 *  {
                 *      string s5455 = e2.ToString();
                 *      s5455 = e2.InnerException.ToString();
                 *  }
                 *  string s = response;
                 * }
                 */

                using (var client = new System.Net.Http.HttpClient()
                {
                    DefaultRequestHeaders = { Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "{SNAeoB88JTmAXfNTAfpR}") }
                })
                {
                    client.BaseAddress = new Uri("https://sandbox.apply-for-teacher-training.service.gov.uk/api/v1");

                    HttpRequestMessage mess = new HttpRequestMessage(HttpMethod.Post, "https://sandbox.apply-for-teacher-training.service.gov.uk/api/v1/test-data/generate");
                    mess.Content = new StringContent("{\"Bearer\": \"SNAeoB88JTmAXfNTAfpR\" \"meta\": { \"attribution\": {\"full_name\":\"ChrisClare\" \"email\":\"[email protected]\" \"user_id\":\"1234\"}} \"timestamp\":\"2019 - 10 - 16T15: 33:49.216Z\"  }");
                    string s    = "{\"Bearer\": \"SNAeoB88JTmAXfNTAfpR\" \"meta\": { \"attribution\": {\"full_name\":\"ChrisClare\" \"email\":\"[email protected]\" \"user_id\":\"1234\"} \"timestamp\":\"2019 - 10 - 16T15: 33:49.216Z\" } }";
                    var    res1 = client.SendAsync(mess).Result;


                    // var response = client.GetAsync("/applications ? since = 2018 - 10 - 01T10:00:00Z");
                    var response = client.GetAsync("/applications? since = 2018 - 10 - 01T10:00:00Z ").Result;
                    response = response;
                }
                return;
            }
        }
Example #45
0
        public ElasticsearchResponse <Stream> DoSyncRequest <T>(string method, Uri uri, byte[] data = null)
        {
            var client = new System.Net.Http.HttpClient();
            HttpResponseMessage response = null;
            HttpContent         content  = null;

            if (data != null)
            {
                content = new ByteArrayContent(data);
            }
            switch (method.ToLower())
            {
            case "head":
                response = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri)).Result;
                break;

            case "delete":
                response = client.SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri)
                {
                    Content = content
                }).Result;
                break;

            case "put":
                response = client.PutAsync(uri, content).Result;
                break;

            case "post":
                response = client.PostAsync(uri, content).Result;
                break;

            case "get":
                response = client.GetAsync(uri).Result;
                break;
            }
            if (response == null)
            {
                return(ElasticsearchResponse <Stream> .CreateError(_settings, null, method, uri.ToString(), data));
            }
            using (var result = response.Content.ReadAsStreamAsync().Result)
            {
                var cs = ElasticsearchResponse <Stream> .Create(this._settings, (int)response.StatusCode, method, uri.ToString(), data, result);

                return(cs);
            }
        }
Example #46
0
        public async static Task <List <Tuple <string, Point> > > GetShuttles(List <string> routeIDs)
        {
            if (!IsThereInternet())
            {
                return(null);
            }

            string routeStr = "";

            foreach (string route in routeIDs)
            {
                routeStr += route + ",";
            }

            // Download stops and get json response
            string url    = "http://api.transloc.com/1.1/vehicles.json?agencies=" + agency + "&routes=" + routeStr;
            var    client = new System.Net.Http.HttpClient();
            HttpResponseMessage response = client.GetAsync(url).Result;
            string responseString        = await response.Content.ReadAsStringAsync();

            JsonObject obj = JsonObject.Parse(responseString);

            var derp  = obj["data"].GetObject();
            var derp2 = derp[agency].GetArray();

            List <Tuple <string, Point> > locsWithIDs = new List <Tuple <string, Point> >();

            foreach (JsonValue val in derp2)
            {
                var    vehicleObj = val.GetObject();
                var    loc        = vehicleObj["location"].GetObject();
                double lat        = loc["lat"].GetNumber();
                double lng        = loc["lng"].GetNumber();
                string routeID    = vehicleObj["route_id"].GetString();
                locsWithIDs.Add(Tuple.Create <string, Point>(routeID, new Point(lat, lng)));
            }

            // cleanup
            obj = null;
            response.Dispose();
            response = null;
            client.Dispose();
            client = null;

            return(locsWithIDs);
        }
Example #47
0
        private async Task <HttpResponseMessage> GetAbsAsync(String action, String param, string mediaType = "application/json")
        {
            using (var handler = new HttpClientHandler {
                Credentials = new System.Net.NetworkCredential(absApiKey, absPassword)
            })
                using (var client = new System.Net.Http.HttpClient(handler))
                {
                    HttpResponseMessage responseMessage = null;
                    client.DefaultRequestHeaders.Add("Authorization", "password " + absPassword);
                    responseMessage = await client.GetAsync(string.Format("{0}v2/{1}?{2}", absEndPoint, action, param));

                    responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
                    string result = await responseMessage.Content.ReadAsStringAsync();

                    return(responseMessage);
                }
        }
Example #48
0
        public async Task <ResponseJsonGeo> Busqueda(string criterio, string Authorization)
        {
            Uri requestUri = new Uri(URL + "/buscar/detalles/" + criterio); //replace your Url
            var objClint   = new System.Net.Http.HttpClient();

            objClint.DefaultRequestHeaders.Add("Authorization", Authorization);
            System.Net.Http.HttpResponseMessage respon = await objClint.GetAsync(requestUri).ConfigureAwait(continueOnCapturedContext: false);

            string responJsonText = await respon.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);

            //MessageBox.Show(respon.ReasonPhrase);
            //MessageBox.Show(responJsonText);
            ResponseJsonGeo objresponseJson = new ResponseJsonGeo();

            objresponseJson = Newtonsoft.Json.JsonConvert.DeserializeObject <ResponseJsonGeo>(responJsonText.ToString());
            return(objresponseJson);
        }
        //Not sure if this is a good way of doing it or not
        public static async Task <List <ProductViewModel> > GetInventoryAsync()
        {
            List <ProductViewModel> productViewModel = null;

            //got info on the HttpCompletionOption from here:
            //https://stackoverflow.com/questions/10343632/httpclient-getasync-never-returns-when-using-await-async
            //http://blog.stephencleary.com/2012/02/async-and-await.html
            //TODO: put this URI into an app setting
            HttpResponseMessage responseMessage = await client.GetAsync("https://petstoreapp.azurewebsites.net/api/products", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

            responseMessage.EnsureSuccessStatusCode();
            if (responseMessage.IsSuccessStatusCode)
            {
                productViewModel = await responseMessage.Content.ReadAsAsync <List <ProductViewModel> >();
            }
            return(productViewModel);
        }
Example #50
0
        static void Ex7()
        {
            string search     = Uri.EscapeDataString("(WebClient OR HttpClient)");
            string language   = Uri.EscapeDataString("fr");
            string requestUri = "http://www.google.com/search?q=" + search + "&hl=" + language;

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            System.Threading.Tasks.Task.Run(async() =>
            {
                using (System.IO.FileStream fs = File.Create("Ex7.html"))
                {
                    var response = await client.GetAsync(requestUri);
                    await response.Content.CopyToAsync(fs);
                }
                System.Diagnostics.Process.Start("Ex7.html");
            });
        }
Example #51
0
 void Test(string url)
 {
     using (var client = new System.Net.Http.HttpClient())
     {
         //using (var response = File.Open(uri, FileMode.Open))
         {
             var res = client.GetAsync(url).Result.Content.ReadAsStreamAsync().Result;
             var doc = AngleSharp.DocumentBuilder.Html(res); //AngleSharp.DOM.Html.HTMLDocument.LoadFromSource(html);
             //doc.LoadHtml(html);
             var a = doc.QuerySelectorAll("//div[@class=\"s-item-container\"]//a");
             if (a != null)
             {
                 Debug.WriteLine(a[0].Attributes["href"].Value.ToString());
             }
         }
     }
 }
Example #52
0
        public async Task TriesToAccessCacheOnFailureButReturnsErrorIfNotInCache()
        {
            // setup
            var    testMessageHandler = new TestMessageHandler(HttpStatusCode.InternalServerError);
            var    cache     = new Mock <IMemoryCache>(MockBehavior.Strict);
            var    cacheTime = TimeSpan.FromSeconds(123);
            object expectedValue;

            cache.Setup(c => c.TryGetValue(this.url, out expectedValue)).Returns(false);
            var client = new System.Net.Http.HttpClient(new InMemoryCacheFallbackHandler(testMessageHandler, TimeSpan.FromDays(1), cacheTime, null, cache.Object));

            // execute
            var result = await client.GetAsync(this.url);

            // validate
            result.StatusCode.Should().Be(HttpStatusCode.InternalServerError);
        }
Example #53
0
        public async Task<List<ChapterViewModels>> GetChapters(string id)
        {
            string html = string.Empty;
            var response = new HttpResponseMessage();
            var endPoint = string.Format("{0}bible/chapters?id={1}", GetBaseUrl(), id);

            using (var client = new System.Net.Http.HttpClient())
            {
                response = await client.GetAsync(endPoint);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var j = await response.Content.ReadAsStringAsync();
                var o = JObject.Parse(j);
                var jo = o["response"]["chapters"];
                var list = JsonConvert.DeserializeObject<List<ChapterViewModels>>(jo.ToString());
                return list;
            }
        }
        public async void GivenUriHasQueryParameterWithSlashes_OnlyRoutePartIsMatched()
        {
            var handler = new TestableMessageHandler();
            var client  = new System.Net.Http.HttpClient(handler);

            handler
            .RespondTo(HttpMethod.Get,
                       "/signin-service/v1/consent/users/840f9c5a-12f6-434f-83c4-6ba605f41092/09b6cbec-cd19-4589-82fd-363dfa8c24da@apps_vw-dilab_com?scopes=address%20profile%20badge%20birthdate%20birthplace%20nationalIdentifier%20nationality%20profession%20email%20vin%20phone%20nickname%20name%20picture%20mbb%20gallery%20openid&relayState=b512822e924ef060fe820c8bbcaabe85859d2035&callback=https://identity.vwgroup.io/oidc/v1/oauth/client/callback&hmac=a63faea3311a0b4296df53ed94d617b241a2e078f080f9997e0d4d9cee2f07f3")
            .With(HttpStatusCode.Found);

            var response = await client.GetAsync("https://identity.vwgroup.io/signin-service/v1/consent/users/840f9c5a-12f6-434f-83c4-6ba605f41092/09b6cbec-cd19-4589-82fd-363dfa8c24da@apps_vw-dilab_com?scopes=address%20profile%20badge%20birthdate%20birthplace%20nationalIdentifier%20nationality%20profession%20email%20vin%20phone%20nickname%20name%20picture%20mbb%20gallery%20openid&relayState=b512822e924ef060fe820c8bbcaabe85859d2035&callback=https://identity.vwgroup.io/oidc/v1/oauth/client/callback&hmac=a63faea3311a0b4296df53ed94d617b241a2e078f080f9997e0d4d9cee2f07f3");

            response
            .StatusCode
            .Should()
            .Be(HttpStatusCode.Found);
        }
        public async void GivenRequestIsConfiguredWithRouteParameters_RequestIsHandled()
        {
            var handler = new TestableMessageHandler();
            var client  = new System.Net.Http.HttpClient(handler);

            handler
            .RespondTo(HttpMethod.Get, "/api/entity/{id}")
            .With(HttpStatusCode.OK)
            .AndContent("application/json", "{\"foo\":\"bar\"}");

            var response = await client.GetAsync("https://tempuri.org/api/entity/123");

            response
            .StatusCode
            .Should()
            .Be(HttpStatusCode.OK);
        }
        public async void GivenWhenCalledActionConfigured_ActionIsCalledWhenRequestIsMade()
        {
            var handler   = new TestableMessageHandler();
            var client    = new System.Net.Http.HttpClient(handler);
            var wasCalled = false;

            handler
            .RespondTo("/api/hello?foo=bar")
            .With(HttpStatusCode.NoContent)
            .WhenCalled(request => wasCalled = true);

            await client.GetAsync("https://tempuri.org/api/hello?foo=bar");

            wasCalled
            .Should()
            .BeTrue();
        }
Example #57
0
        public static ObservableCollection <Guest> LoadGuestsFromJsonAsync()
        {
            using (client)
            {
                client.BaseAddress = new Uri(serverUrl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.GetAsync("api/guests").Result;
                if (response.IsSuccessStatusCode)
                {
                    var guestListe = response.Content.ReadAsAsync <ObservableCollection <Guest> >().Result;

                    return(guestListe);
                }
                return(null);
            }
        }
Example #58
-1
        private async static void Process()
        {
            //获取当前联系人列表
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            IEnumerable<Product> products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            Console.WriteLine("当前联系人列表:");
            ListContacts(products);

            //添加新的联系人
            Product product = new Product { Name = "王五", PhoneNo = "0512-34567890", EmailAddress = "*****@*****.**" };
            await httpClient.PostAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products", product);
            Console.WriteLine("添加新联系人“王五”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);

            //修改现有的某个联系人
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products/001");
            product = (await response.Content.ReadAsAsync<IEnumerable<Product>>()).First();
            product.Name = "赵六";
            product.EmailAddress = "*****@*****.**";
            await httpClient.PutAsJsonAsync<Product>("http://localhost/selfhost/tyz/api/products/001", product);
            Console.WriteLine("修改联系人“001”信息:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);

            //删除现有的某个联系人
            await httpClient.DeleteAsync("http://localhost/selfhost/tyz/api/products/002");
            Console.WriteLine("删除联系人“002”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/tyz/api/products");
            products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
            ListContacts(products);
        }
Example #59
-1
        private static async Task RunTestsAsync(HttpClient client, CancellationToken cancellationToken)
        {
            try
            {
                // SMS                
                await client.PostAsync("/sms/api/sms/unicorn", new StringContent($"\"hello world! ({DateTimeOffset.UtcNow.ToString("u")})\"", Encoding.UTF8, "application/json"), cancellationToken);

                await client.GetAsync("/sms/api/sms/unicorn", cancellationToken);

                // Counter
                await client.PostAsync("/counter/api/counter", new StringContent(string.Empty), cancellationToken);

                await client.GetAsync("/counter/api/counter", cancellationToken);

                await client.GetAsync("/Hosting/CounterService/api/counter", cancellationToken);

                var request = new HttpRequestMessage(HttpMethod.Get, "/api/counter");
                request.Headers.Add("SF-ServiceUri", "fabric:/Hosting/CounterService");
                await client.SendAsync(request, cancellationToken);

                // WebApp
                await client.GetAsync("/webapp", cancellationToken);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #60
-1
        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();
        }