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


C# HttpClient.GetStringAsync方法代码示例

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


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

示例1: Button_Click

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (CountryPhoneCode.SelectedItem != null)
            {
                var _id = Guid.NewGuid().ToString("N");
                var _countryPhoneCode = (CountryPhoneCode.SelectedItem as Country).PhoneCode;
                var _countryName = (CountryPhoneCode.SelectedItem as Country).CountryName;
                var _name = FullName.Text;
                var _phoneNumber = PhoneNumber.Text;
                var _password = Password.Password;

                var client = new HttpClient()
                {
                    BaseAddress = new Uri("http://yochat.azurewebsites.net/chat/")
                };

                var json = await client.GetStringAsync("createuser?id=" + _id + "&fullName=" + _name + "&password=" + _password + "&phoneNumber=" + _phoneNumber + "&countryPhoneCode=" + _countryPhoneCode);

                var serializer = new DataContractJsonSerializer(typeof(User));
                var ms = new MemoryStream();
                var user = serializer.ReadObject(ms) as User;

                Frame.Navigate(typeof(MainPage), user);
            }
            else
            {
                MessageDialog dialog = new MessageDialog("Lütfen Ülkenizi Seçiniz!");
                await dialog.ShowAsync();
            }
        }
开发者ID:yavuzgedik,项目名称:Windows10_UWP,代码行数:30,代码来源:LoginPage.xaml.cs

示例2: GetVideoLink

        private static async Task<string> GetVideoLink(string link)
        {
            var httpClient = new HttpClient();

            var response = await httpClient.GetStringAsync(link);

            var doc = new HtmlDocument();
            doc.LoadHtml(response);

            var iframeLink = doc.DocumentNode.Descendants("body").
                First().
                Descendants("iframe").
                First().
                Attributes["src"].
                Value;

            response = await httpClient.GetStringAsync(iframeLink);

            doc.LoadHtml(response);

            var videoLink = response.Split('\"').
                Where(part =>
                part.Contains(".mp4") && part.StartsWith(@"http://")).
                FirstOrDefault();

            return videoLink;
        }
开发者ID:SamirHafez,项目名称:Fresh,代码行数:27,代码来源:FreeTVCrawlerService.cs

示例3: RefreshAsync

        /// <summary>
        /// 非同步刷新最新資訊
        /// </summary>
        /// <returns></returns>
        public async Task RefreshAsync() {
            HttpClient client = new HttpClient();
            HtmlDocument HTMLDoc = new HtmlDocument();
            HTMLDoc.LoadHtml(await client.GetStringAsync(DataSource));

            var script = HTMLDoc.DocumentNode.Descendants("script")
                .Where(x => x.InnerHtml?.Length > 0).Select(x => x.InnerHtml).ToArray();

            var tempAry = script.First()
                .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                .Select((x, i) => new { index = i, item = x })
                .GroupBy(x => Math.Floor(x.index / 4.0));

            this.LastPassed = null;
            this.Delay = new TimeSpan();

            foreach (var item in tempAry) {
                string[] temp = item.Select(x=>x.item).ToArray();
                if(temp[3] == "TRSearchResult.push('x')") {
                    this.LastPassed = await Station.GetStationByNameAsync(
                        innerString(temp[0],"'","'")
                        );
                }                
            }

            var time = new TimeSpan(0, int.Parse(innerString(script.Last(), "=", ";")),0);
            this.Delay= time;
        }
开发者ID:XuPeiYao,项目名称:TwOpenData.Railways,代码行数:32,代码来源:RealTimeTrainInfo.cs

示例4: GetLink

        public async Task<string> GetLink(string tvShow, int season, int episode, params string[] exclude)
        {
            tvShow = tvShow.Replace("&", "and");

            var encodedString = WebUtility.UrlEncode(tvShow);
            var httpClient = new HttpClient();

            var response = await httpClient.GetStringAsync(string.Format(FreeTvQuery, FreeTv, encodedString));

            IList<string> results = GetQueryResults(response);

            var first = results[0];

            response = await httpClient.GetStringAsync(string.Format(FreeTv + first + FreeTvSeason, season));

            foreach (var link in GetEpisodeLinks(response, episode))
                try
                {
                    var videoLink = await GetVideoLink(link);

                    if (videoLink == null)
                        continue;

                    return videoLink;
                }
                catch
                { }

            return null;
        }
开发者ID:SamirHafez,项目名称:Fresh,代码行数:30,代码来源:FreeTVCrawlerService.cs

示例5: MainAsync

        private static async Task MainAsync()
        {
            // configure
            var settings = new TorSharpSettings
            {
                ZippedToolsDirectory = Path.Combine(Path.GetTempPath(), "TorZipped"),
                ExtractedToolsDirectory = Path.Combine(Path.GetTempPath(), "TorExtracted"),
                PrivoxyPort = 1337,
                TorSocksPort = 1338,
                TorControlPort = 1339,
                TorControlPassword = "foobar",
                ToolRunnerType = ToolRunnerType.Simple
            };

            // download tools
            await new TorSharpToolFetcher(settings, new HttpClient()).FetchAsync();

            // execute
            var proxy = new TorSharpProxy(settings);
            var handler = new HttpClientHandler
            {
                Proxy = new WebProxy(new Uri("http://localhost:" + settings.PrivoxyPort))
            };
            var httpClient = new HttpClient(handler);
            await proxy.ConfigureAndStartAsync();
            Console.WriteLine(await httpClient.GetStringAsync("http://icanhazip.com"));
            await proxy.GetNewIdentityAsync();
            Console.WriteLine(await httpClient.GetStringAsync("http://icanhazip.com"));
            proxy.Stop();
        }
开发者ID:JSkimming,项目名称:TorSharp,代码行数:30,代码来源:Program.cs

示例6: LibraryInfoAsync

		public static async Task<IEnumerable<FileInfo>> LibraryInfoAsync (string Category)
		{
			string result = null; 
			IEnumerable<FileInfo> data;
			var client = new HttpClient ();
			try 
			{
				result = await client.GetStringAsync (WebApiUrls.Library);
				 data = JsonConvert.DeserializeObject<IEnumerable<FileInfo>> (result).ToList ();
				//return data.Where (i => i.Category == Category).AsEnumerable ();
			} 
			catch 
			{
				result = await client.GetStringAsync (WebApiUrls.Library);
				 data = JsonConvert.DeserializeObject<IEnumerable<FileInfo>> (result).ToList ();
				//return data.Where (i => i.Category == Category).AsEnumerable ();
			}

			if (Category != "All") {
				data = data.Where (i => i.Category == Category).AsEnumerable ();
			} else {
				data = data.Where (i => i.Category != "newsletter").AsEnumerable ();
			}
			return data;
		}
开发者ID:CorningWebServices,项目名称:SolutionsKiosk,代码行数:25,代码来源:Library.cs

示例7: Download

        static async Task Download(string id, string path)
        {
            var index = new Uri(string.Format("https://api.nuget.org/v3/registration1/{0}/index.json", id.ToLowerInvariant()));

            HttpClient client = new HttpClient();

            string jsonIndex = await client.GetStringAsync(index);
            JObject objIndex = JObject.Parse(jsonIndex);

            File.WriteAllText(path + "index.json", jsonIndex);

            foreach (var item in objIndex["items"])
            {
                string pageUri = item["@id"].ToString();

                Console.WriteLine("{0}", pageUri);

                string jsonPage = await client.GetStringAsync(pageUri);
                JObject jsonObj = JObject.Parse(jsonPage);

                var lower = item["lower"];
                var upper = item["upper"];

                string filename = string.Format("{0}_{1}_{2}.json", id.ToLowerInvariant(), lower, upper);

                File.WriteAllText(path + filename, jsonPage);
            }
        }
开发者ID:NuGet,项目名称:Entropy,代码行数:28,代码来源:Program.cs

示例8: Load

 public async Task Load()
 {
     var cli = new HttpClient();
     var res = await cli.GetStringAsync("http://api.openweathermap.org/data/2.5/weather?q=Moscow&mode=json&units=metric&APPID=" + AppID);
     dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
     Temperature = x.main.temp;
     Pic = new BitmapImage(new Uri($"http://openweathermap.org/img/w/{x.weather[0].icon}.png"));
     if (PropertyChanged!=null)
     {
         PropertyChanged(this,new PropertyChangedEventArgs("Temperature"));
         PropertyChanged(this,new PropertyChangedEventArgs("Pic"));
     }
     res = await cli.GetStringAsync("http://api.openweathermap.org/data/2.5/forecast/daily?q=Moscow&mode=json&units=metric&cnt=7&APPID="+AppID);
     x = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
     foreach (var z in x.list)
     {
         Forecast.Add(new WeatherRecord()
         {
             When = Convert((long)z.dt),
             Temp = z.temp.day,
             Pressure = z.pressure,
             Humidity = z.humidity,
             Icon = new BitmapImage(new Uri($"http://openweathermap.org/img/w/{z.weather[0].icon}.png"))
         });
     }
 }
开发者ID:evangelism,项目名称:Win10UWPCourse,代码行数:26,代码来源:WeatherViewModel.cs

示例9: GetWebSiteContent

 private async static Task GetWebSiteContent()
 {
     HttpClient client = new HttpClient();
     try
     {
         var result = await client.GetStringAsync("http://www.firstcrazydeveloper.com");
         WriteLine(result);
     }
     catch (Exception exception)
     {
         try
         {
             //This asynchronous request will run if the first request failed. 
             var result = await client.GetStringAsync("http://www.codingalmanac.com");
             WriteLine(result);
         }
         catch
         {
             WriteLine("Entered Catch Block");
         }
         finally
         {
             WriteLine("Entered Finally Block");
         }
     }
 }
开发者ID:Kasiviswanathan3876,项目名称:NewFeatureCSharp6,代码行数:26,代码来源:AwaitWithCatchBlock.cs

示例10: CheckAuth

		public static async Task<Exception> CheckAuth(string id, string pass,SQLiteConnection connection)
		{
			pass = base64Encode (pass);
			var httpClient = new HttpClient ();
			Exception  error;
			httpClient.Timeout = TimeSpan.FromSeconds (20);
			string contents;
			Task<string> contentsTask = httpClient.GetStringAsync ("http://www.schoolapi.somee.com/dangnhap/"+id+"/"+pass);

			try
			{
				contents =  await contentsTask;

			}
			catch(Exception e) {
				error =new Exception("Xảy Ra Lỗi Trong Quá Trình Kết Nối Server");
				return error;
			}
			if (contents.Contains ("false")) {
				error=new Exception("Mã Sinh Viên Hoặc Mật Khẩu Không Đúng");
				return error;

			}
			User usr = new User ();
			usr.Password = pass;
			usr.Id = id;
			Task<string> contentNameTask = httpClient.GetStringAsync ("http://www.schoolapi.somee.com/user/" + id);
			contents=await contentNameTask;
			XDocument doc = XDocument.Parse (contents);
			usr.Hoten= doc.Root.Elements().ElementAt(0).Elements().ElementAt(1).Value.ToString();
			int i = AddUser (connection, usr);
			return null;
		}
开发者ID:tienbui123,项目名称:Mobile-VS2,代码行数:33,代码来源:BUser.cs

示例11: GetLink

        public async Task<string> GetLink(string tvShow, int season, int episode, params string[] exclude)
        {
            var encodedString = WebUtility.UrlEncode(tvShow);
            var httpClient = new HttpClient();

            var response = await httpClient.GetStringAsync(string.Format(LetMeWatchThisQuery, LetMeWatchThis, encodedString));

            IList<string> results = GetQueryResults(response);

            var first = results[0];

            response = await httpClient.GetStringAsync(LetMeWatchThis + first);

            foreach (var link in await GetEpisodeLinks(response, season, episode))
                try
                {
                    var videoLink = await GetVideoLink(link);

                    if (videoLink == null || exclude.Contains(videoLink))
                        continue;

                    return videoLink;
                }
                catch
                { }

            return null;
        }
开发者ID:SamirHafez,项目名称:Fresh,代码行数:28,代码来源:LetMeWatchThisCrawlerService.cs

示例12: Button_Click

 private async void Button_Click(object sender, RoutedEventArgs e)
 {
     var cli = new HttpClient();
     await cli.GetStringAsync($"{uri}/User/{uname.Text}");
     var res = await cli.GetStringAsync($"{uri}/User");
     var ulist = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(res);
     lb.ItemsSource = ulist;
 }
开发者ID:GoreMaria,项目名称:HackSamples,代码行数:8,代码来源:MainPage.xaml.cs

示例13: ExecuteMultipleRequests

        public async Task ExecuteMultipleRequests()
        {
            var client = new HttpClient();

            string microsoft = await client.GetStringAsync("http://www.microsoft.com");
            string msdn = await client.GetStringAsync("http://msdn.microsoft.com");
            string blogs = await client.GetStringAsync("http://blogs.msdn.com/");
        }
开发者ID:rrsc,项目名称:ProgrammingInCSharp,代码行数:8,代码来源:ExecutingMultipleAwaits.cs

示例14: ExecuteMultipleRequestsInParallel

 public async Task ExecuteMultipleRequestsInParallel()
 {
     HttpClient client = new HttpClient();
     Task microsoft = client.GetStringAsync("http://www.microsoft.com");
     Task msdn = client.GetStringAsync("http://msdn.microsoft.com");
     Task blogs = client.GetStringAsync("http://blogs.msdn.com/");
     await Task.WhenAll(microsoft, msdn, blogs);
 }
开发者ID:ErhanGDC,项目名称:MyWorks,代码行数:8,代码来源:Program.cs

示例15: GetString_RelativeUri

        public void GetString_RelativeUri()
        {
            var client = new HttpClient ();
            client.BaseAddress = new Uri ("http://en.wikipedia.org/wiki/");
            var uri = new Uri ("Computer", UriKind.Relative);

            Assert.That (client.GetStringAsync (uri).Result != null);
            Assert.That (client.GetStringAsync ("Computer").Result != null);
        }
开发者ID:baulig,项目名称:martins-playground,代码行数:9,代码来源:Test.cs


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