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


C# HttpClient.GetStreamAsync方法代码示例

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


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

示例1: Main

 static void Main(string[] args)
 {
     string address = "http://127.0.0.1:645";
     Uri uri = new Uri(address);
     Console.WriteLine(uri.AbsolutePath); 
     HttpClient http = new HttpClient();
     HttpClientHandler cd = new HttpClientHandler();
     HttpContent hc = 
     
     http.GetStreamAsync(uri);
     Console.WriteLine(http.GetStreamAsync(uri).Result.ToString());
     Console.ReadLine();
 }
开发者ID:kenobit,项目名称:Valtech_tasks,代码行数:13,代码来源:Program.cs

示例2: UploadJpegPhoto

        public async Task UploadJpegPhoto()
        {
            IPlanGridApi client = PlanGridClient.Create();
            Stream payload = typeof(PhotoTests).Assembly.GetManifestResourceStream("PlanGrid.Api.Tests.TestData.Sample.jpg");
            Photo photo = await client.UploadPngPhoto(TestData.Project2Uid, "test name", payload);

            Assert.AreEqual("test name", photo.Title);
            Assert.AreEqual(TestData.ApiTestsUserUid, photo.CreatedBy.Uid);
            Assert.AreNotEqual(photo.CreatedAt, default(DateTime));

            using (var downloader = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip, AllowAutoRedirect = true }))
            {
                Stream returnedPayload = await downloader.GetStreamAsync(photo.Url);
                payload = typeof(PhotoTests).Assembly.GetManifestResourceStream("PlanGrid.Api.Tests.TestData.Sample.jpg");
                var payloadBytes = new MemoryStream();
                await payload.CopyToAsync(payloadBytes);
                var returnedBytes = new MemoryStream();
                await returnedPayload.CopyToAsync(returnedBytes);
                Assert.IsTrue(payloadBytes.ToArray().SequenceEqual(returnedBytes.ToArray()));
            }

            Photo retrievedPhoto = await client.GetPhotoInProject(TestData.Project2Uid, photo.Uid);
            Assert.AreEqual("test name", retrievedPhoto.Title);
            await client.UpdatePhoto(TestData.Project2Uid, photo.Uid, new PhotoUpdate { Title = "new title" });
            retrievedPhoto = await client.GetPhotoInProject(TestData.Project2Uid, photo.Uid);
            Assert.AreEqual("new title", retrievedPhoto.Title);

            Assert.IsFalse(retrievedPhoto.IsDeleted);
            await client.RemovePhoto(TestData.Project2Uid, photo.Uid);
            Photo removedPhoto = await client.GetPhotoInProject(TestData.Project2Uid, photo.Uid);
            Assert.IsTrue(removedPhoto.IsDeleted);
        }
开发者ID:plangrid,项目名称:plangrid-api-net,代码行数:32,代码来源:PhotoTests.cs

示例3: DownloadInParallel

        private static void DownloadInParallel(IEnumerable<Show> showsToDownload)
        {
            var po = new ParallelOptions {MaxDegreeOfParallelism = MaxSimultaneousDownloads};
            Parallel.ForEach(showsToDownload, po, show =>
                {
                    try
                    {
                        using (var httpClient = new HttpClient())
                        {
                            var downloadStream = httpClient.GetStreamAsync(show.Mp3Uri).Result;

                            var file = new FileInfo(_saveDirectory + string.Format(@"\Hanselminutes_{0}.mp3", show.Id));
                            using (downloadStream)
                            using (var fileStream = file.Create())
                            {
                                Console.WriteLine(string.Format("Downloading show {0}", show.Id));
                                downloadStream.CopyTo(fileStream);
                            }

                            Console.WriteLine(string.Format("Show {0} downloaded to {1}", show.Id, file));
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e);
                    }
                });
        }
开发者ID:AndreasPresthammer,项目名称:HanselDownloader,代码行数:28,代码来源:Program.cs

示例4: LoadToStream

        public static async Task<Stream> LoadToStream(this Uri source)
        {
#if NETFX_CORE || (WINDOWS_PHONE && !WINDOWS_PHONE7)
            switch (source.Scheme.ToLowerInvariant())
            {
                case "ms-appx":
                case "ms-appdata":
                    var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(source);
                    return await file.OpenStreamForReadAsync();
                default:
                    using (var client = new HttpClient())
                    {
                        using (var stream = await client.GetStreamAsync(source))
                        {
                            var result = new MemoryStream();
                            await stream.CopyToAsync(result);
                            result.Seek(0, SeekOrigin.Begin);
                            return result;
                        }
                    }
            }
#else
            using (var client = new HttpClient())
            {
                return await client.GetStreamAsync(source);
            }
#endif
        }
开发者ID:bondarenkod,项目名称:pf-arm-deploy-error,代码行数:28,代码来源:Extensions.cs

示例5: LoginInitAndGetloginVcode

 public static async Task<Image> LoginInitAndGetloginVcode(bool IsFirst = false)
 {
     try
     {
         var handler = new HttpClientHandler() { CookieContainer = cookieContainers, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.GZip };
         using (var httpClient = new HttpClient(handler))
         {
             httpClient.DefaultRequestHeaders.Add("Host", "kyfw.12306.cn");
             httpClient.DefaultRequestHeaders.Add("Origin", ConstantKey.loginorigin);
             httpClient.DefaultRequestHeaders.Add("Referer", ConstantKey.loginRefer);
             httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131");
             ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
             if (IsFirst)
             {
                 //loginInit
                 string loginInit = await httpClient.GetStringAsync(ConstantKey.loginInit);
                 if (string.IsNullOrEmpty(loginInit) || !loginInit.Contains("登录")) return null;
                 //loginJs
                 var resp = await httpClient.GetAsync(ConstantKey.loginJs);
                 if (!resp.IsSuccessStatusCode) return null;
             }
             //VerifyCode
             var verifyStream = await httpClient.GetStreamAsync(ConstantKey.loginVcode);
             if (verifyStream == null) return null;
             return Image.FromStream(verifyStream);
         }
     }
     catch (Exception ex)
     {
         return null;
     }
 }
开发者ID:zhouyongtao,项目名称:TicketHelper,代码行数:32,代码来源:TicketHandler.cs

示例6: DoJSON

        //gets the summoner name from the search form and finds the corresponding ID 
        //then calls to create the 3 api files
        static async Task<bool> DoJSON(string summonerName)
        {
            _sem.WaitOne();
            string apikey = ConfigurationManager.AppSettings.Get("apikey");
            string nameinfo = summonerName;
            string path = ConfigurationManager.AppSettings.Get("path");
            var client = new HttpClient();

            Stream nameInfo = await client.GetStreamAsync("https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/" + nameinfo + "?api_key=" + apikey);
            Thread.Sleep(1100);

            DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
            settings.UseSimpleDictionaryFormat = true;
            DataContractJsonSerializer userser = new DataContractJsonSerializer(typeof(Dictionary<string, Summoner>), settings);
            Dictionary<string, Summoner> userDict = (Dictionary<string, Summoner>)userser.ReadObject(nameInfo);

            string key = userDict.Keys.First<string>();
            id = userDict[key].id;

            leaguedata.LocalFileGen files = new leaguedata.LocalFileGen();
            if (!File.Exists(path + "champs.txt"))
            {
                int x = await files.ChampInfoFile();
            }
            if (!File.Exists(path + "history" + nameinfo + ".txt"))
            {
                int x = await files.MatchHistoryFile(nameinfo, id);
            }
            leaguedata.leagueDictionaries dicts = new leaguedata.leagueDictionaries();
            Dictionary<int, string> champIDtoName = dicts.getCIDtoCName();
            List<Match> matches = dicts.getMatchList(nameinfo);
            int y = await files.MatchInfoFile(nameinfo, matches, champIDtoName);
            _sem.Release();
            return true;
        }
开发者ID:eli4,项目名称:leagueprogram,代码行数:37,代码来源:leagueInfo.cs

示例7: GetResponseStreamAsync

 public static async Task<Stream> GetResponseStreamAsync(string url,
     IEnumerable<KeyValuePair<string, string>> headers = null, RequestHttpMethod method = RequestHttpMethod.Get)
 {
     if (string.IsNullOrWhiteSpace(url))
         throw new ArgumentNullException(nameof(url));
     var httpClient = new HttpClient();
     switch (method)
     {
         case RequestHttpMethod.Get:
             if (headers != null)
             {
                 foreach (var header in headers)
                 {
                     httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                 }
             }
             return await httpClient.GetStreamAsync(url);
         case RequestHttpMethod.Post:
             FormUrlEncodedContent formContent = null;
             if (headers != null)
             {
                 formContent = new FormUrlEncodedContent(headers);
             }
             var message = await httpClient.PostAsync(url, formContent);
             return await message.Content.ReadAsStreamAsync();
         default:
             throw new NotImplementedException("That type of request is unsupported.");
     }
 }
开发者ID:magicvoid1,项目名称:NadekoBot,代码行数:29,代码来源:SearchHelper.cs

示例8: OnLoad

 protected override void OnLoad(EventArgs e)
 {
     var client = new HttpClient();
     client.DefaultRequestHeaders.Add("ServiceBusAuthorization", this.sendToken);
     var image = client.GetStreamAsync(this.sendAddress + "/image").GetAwaiter().GetResult();
     this.pictureBox.Image = Image.FromStream(image);
 }
开发者ID:lokeshsp,项目名称:azure-servicebus-relay-samples,代码行数:7,代码来源:ClientForm.cs

示例9: GetSdkPathAsync

		public static async Task<string> GetSdkPathAsync()
		{
			string result = Environment.GetEnvironmentVariable("DART_SDK", EnvironmentVariableTarget.Process);
			if (!Directory.Exists(result))
			{
				string extensionName = "DartVS";
				string extensionVersion = AssemblyInfo.AssemblyInformationalVersion;
				string tempDir = Path.Combine(Path.GetTempPath(), string.Format("{0}-{1}-sdk", extensionName, extensionVersion));
				result = Path.Combine(tempDir, "dart-sdk");
				if (!Directory.Exists(result))
				{
					// TODO: This code might have issues if two threads ask or the SDK at the same time and we need to download it...
					// Thread1 will start the download.
					// Thread2 will skip this code (DirectoryExists; unless we're very unlucky with timing), then crash on
					// the File.Exists check for dart.exe.

					Directory.CreateDirectory(tempDir);
					string sdkName = "dartsdk-windows-ia32-release.zip";
					string compressed = Path.Combine(tempDir, sdkName);

					using (var httpClient = new HttpClient())
					using (var stream = await httpClient.GetStreamAsync(RemoteSdkZipUrl).ConfigureAwait(false))
					using (var outputStream = File.OpenWrite(compressed))
						await stream.CopyToAsync(outputStream).ConfigureAwait(false);

					ZipFile.ExtractToDirectory(compressed, tempDir);
				}
			}

			if (!Directory.Exists(result) || !File.Exists(Path.Combine(result, "bin", "dart.exe")))
				throw new NotSupportedException("Could not locate or download the Dart SDK. All analysis is disabled.");

			return result;
		}
开发者ID:modulexcite,项目名称:DartVS,代码行数:34,代码来源:DartSdk.cs

示例10: getUser

        /// <summary>
        /// Get basic user info
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public static async Task getUser(string user_id)
        {
            string baseURL = App.baseURL;
            HttpClient client = new HttpClient();

            if (App.logged_in == false && user_id == "__SELF__")    
            {
                // error if trying to access the logged in user and there is none
                return;
            }
            else if(App.logged_in == false)     // not logged in
            {
                baseURL = string.Format("{0}/users/{1}", baseURL, user_id);
            }
            else if(App.logged_in == true)      // logged in
            {
                baseURL = string.Format("{0}/users/{1}", baseURL, user_id);
                List<Parameter> parameters = new List<Parameter>();
                baseURL = AuthenticationAccess.addAuthentication(baseURL, parameters);
            }

            try
            {
                var jsonStream = await client.GetStreamAsync(baseURL);
                //var jsonString = await client.GetStringAsync(baseURL);
            }
            catch
            {

            }

            return;
        }
开发者ID:CarltonSemple,项目名称:WindowsApps,代码行数:38,代码来源:UserAccess.cs

示例11: PullHtml

        public string PullHtml(string url)
        {
            var client = new HttpClient();
            var urlStreamTask = client.GetStreamAsync(url);
            var responseTask = urlStreamTask.ContinueWith(response => {
                if (response.Exception != null) {
                    throw response.Exception;
                }

                using (var memoryStream = new MemoryStream()) {
                    response.Result.CopyTo(memoryStream);
                    //默认按utf8编码读取html
                    string html = ReadHtml(memoryStream, Encoding.UTF8);

                    //根据html的charset判断编码类型
                    Match charSetMatch = Regex.Match(html, "charset=(?<code>[a-zA-Z0-9_-]+)", RegexOptions.IgnoreCase);
                    string chartSet = charSetMatch.Groups["code"].Value;
                    if (!string.IsNullOrEmpty(chartSet) && !chartSet.Equals("utf-8", StringComparison.OrdinalIgnoreCase)) {
                        html = ReadHtml(memoryStream, Encoding.GetEncoding(chartSet));
                    }

                    return html;
                }
            });

            return responseTask.Result;
        }
开发者ID:coolcode,项目名称:app,代码行数:27,代码来源:PullService.cs

示例12: GetBijinPicture

        public async Task<BitmapImage> GetBijinPicture(string Path)
        {
            var date = DateTime.Now;
            var url = "http://www.bijint.com/" + Path + "/tokei_images/" + date.ToString("HHmm") + ".jpg";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Referrer = new Uri("http://www.bijint.com/" + Path);
            BitmapImage bitmap;
            using (var strm = await client.GetStreamAsync(new Uri(url)))
            {
                // BitmapImageインスタンスへはStream型をそのまま読み込ませることができないため、
                // InMemoryRandomAccessStreamへソースストリームをコピーする
                InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
                var output = ims.GetOutputStreamAt(0);
                await RandomAccessStream.CopyAsync(strm.AsInputStream(), output);

                // BitmapImageへソースを設定し、Imageコントロールで表示させる
                bitmap = new BitmapImage();
                bitmap.SetSource(ims);
            }
            return bitmap;

            //var html = await client.GetStringAsync("http://www.bijint.com/kobe/cache/" + date.ToString("HHmm") + ".html");
            //this.html.NavigateToString(html);
        }
开发者ID:posaunehm,项目名称:MyBeautyClock,代码行数:25,代码来源:BeautyDataFactory.cs

示例13: GetInfoAsync

        private static Task<string> GetInfoAsync(string uri)
        {
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
            var client = new HttpClient();
            var streamTask = client.GetStreamAsync(uri);

            streamTask.ContinueWith(
                _ =>
                {
                    if (streamTask.IsCompleted)
                    {
                        var result = streamTask.Result;
                        var stringResult = new StreamReader(result).ReadToEnd();
                        tcs.TrySetResult(stringResult);
                    }
                    else
                    {
                        if (streamTask.IsCanceled)
                        {
                            tcs.TrySetCanceled();
                        }
                        else
                        {
                            tcs.TrySetException(streamTask.Exception.InnerExceptions);
                        }
                    }
                }
            );

            return tcs.Task;
        }
开发者ID:luismdcp,项目名称:PROMPT11-07-ConcurrentProgramming.luismdcp.TrabalhoFinal,代码行数:31,代码来源:ConcurrentCache.cs

示例14: GetImageStreamAsync

		public static async Task<Stream> GetImageStreamAsync(CameraModel camera)
		{
			var http = new HttpClient();
			http.DefaultRequestHeaders.Authorization = GetAuthenticationHeader(camera);

			return await http.GetStreamAsync(camera.Url);
		}
开发者ID:andy-uq,项目名称:CamTastic,代码行数:7,代码来源:CameraController.cs

示例15: GetBijinPicture

        private async void GetBijinPicture()
        {
            var date = DateTime.Now;
            var url = "http://www.bijint.com/jp/tokei_images/" + date.ToString("HHmm") + ".jpg";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Referrer = new Uri("http://www.bijint.com/jp/");
            using (var strm = await client.GetStreamAsync(new Uri(url)))
            {
                // BitmapImageインスタンスへはStream型をそのまま読み込ませることができないため、
                // InMemoryRandomAccessStreamへソースストリームをコピーする
                InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
                var output = ims.GetOutputStreamAt(0);
                await RandomAccessStream.CopyAsync(strm.AsInputStream(), output);

                // BitmapImageへソースを設定し、Imageコントロールで表示させる
                var bitmap = new BitmapImage();
                bitmap.SetSource(ims);
                image.Source = bitmap;

                // Save用にbyte配列に保存
                ims.Seek(0);
                imageBuffer = new byte[ims.Size];
                IBuffer ibuffer = imageBuffer.AsBuffer();
                await ims.ReadAsync(ibuffer, (uint)ims.Size, InputStreamOptions.None);
            }
        }
开发者ID:KarinoTaro,项目名称:MetroDokei,代码行数:27,代码来源:MainPage.xaml.cs


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