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


C# HttpClient.GetByteArrayAsync方法代码示例

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


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

示例1: Download

        private async Task Download(string url,StorageFile file,bool cover)
        {
            var http = new HttpClient();
            byte[] response = { };
            string betterUrl = url;
            if(cover)
            {
                var pos = betterUrl.IndexOf(".jpg");
                if (pos != -1)
                    betterUrl = betterUrl.Insert(pos, "l");
            }

            //get bytes
            try
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(betterUrl));
            }
            catch (Exception)
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(url));
            }

            var fs = await file.OpenStreamForWriteAsync(); //get stream
            var writer = new DataWriter(fs.AsOutputStream());

            writer.WriteBytes(response); //write
            await writer.StoreAsync();
            await writer.FlushAsync();

            writer.Dispose();
        }
开发者ID:Mordonus,项目名称:MALClient,代码行数:31,代码来源:ImageDownloaderService.cs

示例2: Parse

        /// <summary>
        /// Parser article from URL.
        /// </summary>
        /// <param name="url">URL</param>
        /// <returns></returns>
        public static String Parse(String url)
        {
            String source;
            byte[] response;
            HtmlNode content;
            HttpClient client;
            HtmlDocument document;
            List<String> sentences;

            sentences = new List<String>();
            client = new HttpClient();
            response = client.GetByteArrayAsync(url).Result;
            source = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
            source = WebUtility.HtmlDecode(source);
            document = new HtmlDocument();
            document.LoadHtml(source);

            content = document.DocumentNode.Descendants().Where(
                x => x.Attributes["id"] != null && x.Attributes["id"].Value.Equals("mw-content-text")).FirstOrDefault();

            if (content == null)
                return "Unable to parse the source.";

            foreach (HtmlNode childNoteLoop in content.ChildNodes)
            {
                if (childNoteLoop.Name == "div" && childNoteLoop.Id == "toc")
                    break;

                if (childNoteLoop.Name == "p")
                    sentences.Add(childNoteLoop.InnerText.Trim());
            }

            return String.Join(NotenizerConstants.WordDelimeter, sentences);
        }
开发者ID:nemcek,项目名称:notenizer,代码行数:39,代码来源:WikiParser.cs

示例3: OnCreate

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);

			// Get our button from the layout resource,
			// and attach an event to it
			Button AsyncButton = FindViewById<Button> (Resource.Id.btnAsync);
			Button ParallelButton = FindViewById<Button> (Resource.Id.btnParallel);
			TextView LabelSize = FindViewById<TextView> (Resource.Id.lblSize);
			ImageView ImageDonwloaded = FindViewById<ImageView> (Resource.Id.imageD);
			CheckBox ckbHUD = FindViewById<CheckBox> (Resource.Id.checkBoxHUD);
			var showHUD = false;

			ParallelButton.Click += (sender, e) => {
				showHUD = ckbHUD.Checked;
				Task.Factory.StartNew(()=>{
					if(showHUD)
						AndHUD.Shared.Show(this, "Downloading Image via Parallel", -1, MaskType.Clear);
					var httpClient = new HttpClient();
					byte[] imageBytes  = httpClient.GetByteArrayAsync("http://upload.wikimedia.org/wikipedia/commons/6/66/Big_size_chess_6759_CRI_08_2009_Langosta_Beach.jpg").Result;
					return imageBytes; 
				}).ContinueWith(res=>{
					string documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
					string localPath = System.IO.Path.Combine (documents, "image.png");
					File.WriteAllBytes (localPath, res.Result);
					var localImage = new Java.IO.File (localPath);
					if (localImage.Exists ()) {
						var teamBitmap = BitmapFactory.DecodeFile (localImage.AbsolutePath);
						RunOnUiThread(()=>{
							LabelSize.Text = string.Format("Size: {0} MB", ConvertBytesToMegabytes(res.Result.Length));
							ImageDonwloaded.SetImageBitmap (teamBitmap);
						});
					}
					if(showHUD)
						AndHUD.Shared.Dismiss(this);
				});
			};

			AsyncButton.Click += async (sender, e) => {
				showHUD = ckbHUD.Checked;
				if(showHUD)
					AndHUD.Shared.Show(this, "Downloading Image via Async/Await", -1, MaskType.Clear);
				var httpClient = new HttpClient();
				byte[] imageBytes  = await httpClient.GetByteArrayAsync("http://upload.wikimedia.org/wikipedia/commons/6/66/Big_size_chess_6759_CRI_08_2009_Langosta_Beach.jpg");
				string documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
				string localPath = System.IO.Path.Combine (documents, "image.png");
				File.WriteAllBytes (localPath, imageBytes);
				var localImage = new Java.IO.File (localPath);
				if (localImage.Exists ()) {
					var teamBitmap = BitmapFactory.DecodeFile (localImage.AbsolutePath);
					LabelSize.Text = string.Format("Size: {0} MB", ConvertBytesToMegabytes(imageBytes.Length));
					ImageDonwloaded.SetImageBitmap (teamBitmap);
				}
				if(showHUD)
					AndHUD.Shared.Dismiss(this);
			};
		}
开发者ID:EnriqueProinfo,项目名称:Mono,代码行数:60,代码来源:MainActivity.cs

示例4: BeginReadCCTV

       async  void BeginReadCCTV()
        {
            
            IsBeginRead = true;
            ISExit = false;
            tblCCTV cctvinfo=null;
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                   () =>
                   {
                       cctvinfo = this.DataContext as tblCCTV;
                   });

             
           // client=new HttpClient();
            while (!ISExit)
            {
                try
                {
                    Uri uri = new Uri("http://192.192.161.3/" + cctvinfo.REF_CCTV_ID.Trim() + ".jpg?" + rnd.Next(), UriKind.Absolute);

                    using (httpClient = new HttpClient())
                    {
                        httpClient.Timeout = TimeSpan.FromSeconds(0.5);
                        var contentBytes = await httpClient.GetByteArrayAsync(uri);

                   
                        var ims =  new InMemoryRandomAccessStream();

                        var dataWriter = new DataWriter(ims);
                        dataWriter.WriteBytes(contentBytes);
                        await dataWriter.StoreAsync();
                       //ims.seak 0
                     ims.Seek(0 );
                       
                       await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal,()=>
                            {
                        BitmapImage bitmap = new BitmapImage();
                        bitmap.SetSource(ims );
                       

                        this.imgCCTV.Source = bitmap;
                        imginx = (imginx + 1) % 90000;
                        this.RunFrameRate.Text = imginx.ToString();
                            });
                    }
                    
                }
                catch (Exception ex)
                {
                 //   this.textBlock1.Text = ex.Message;
                }
                // BitmapImage img = new BitmapImage();
                // img.SetSource(stream);

              

               
            }
        
        }
开发者ID:ufjl0683,项目名称:sshmc,代码行数:60,代码来源:CCTV.xaml.cs

示例5: GetByteArrayAsync

 public async static Task<byte[]> GetByteArrayAsync(string url)
 {
     using (var httpClient = new HttpClient(new ModernHttpClient.NativeMessageHandler()))
     {
         return await httpClient.GetByteArrayAsync(url);
     }
 }
开发者ID:jamesmontemagno,项目名称:PuppyKittyOverflow,代码行数:7,代码来源:OverflowHelper.cs

示例6: DownloadFromUri

        public Task<byte[]> DownloadFromUri(string uri)
        {
            //HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);

            //using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
            //{
            //    using (Stream stream = httpWebReponse.GetResponseStream())
            //    {
            //        var memoryStream = new MemoryStream();
            //        stream.CopyTo(memoryStream);
            //        return memoryStream.ToArray();
            //    }
            //}

            return Task.Run(async () =>
             {
                 using (var client = new HttpClient())
                 {
                      // var stream = client.GetStreamAsync("https://scontent-frt3-1.xx.fbcdn.net/hphotos-xat1/v/t1.0-9/12289642_1183804578301916_8282521644435051935_n.jpg?oh=3f6d4458591beda5ca286d4269ecb865&oe=5724CC7F");
                      var rawresponse = await  client.GetByteArrayAsync(uri);

                     return rawresponse;// TODO:
                  }

             });
        }
开发者ID:MariyaSteffanova,项目名称:EcoMaster,代码行数:26,代码来源:ImageDownloaderService.cs

示例7: DownloadHomepageAsync

		public async Task<int> DownloadHomepageAsync()
		{
			var httpClient = new HttpClient(); // Xamarin supports HttpClient!

			Task<string> contentsTask = httpClient.GetStringAsync("http://xamarin.com"); // async method!

			ResultEditText.Text += "DownloadHomepage method continues after async call. . . . .\n";

			// await! control returns to the caller and the task continues to run on another thread
			string contents = await contentsTask;

			// After contentTask completes, you can calculate the length of the string.
			int exampleInt = contents.Length;

			ResultEditText.Text += "Downloaded the html and found out the length.\n\n\n";




			byte[] imageBytes  = await httpClient.GetByteArrayAsync("http://xamarin.com/images/about/team.jpg"); // async method!

			string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
			string localFilename = "team.jpg";
			string localPath = Path.Combine (documentsPath, localFilename);
			File.WriteAllBytes (localPath, imageBytes); // writes to local storage   

			ResultTextView.Text += "Downloaded the image.\n";

			// ImageView stuff goes here

			ResultEditText.Text += contents; // just dump the entire HTML
			return exampleInt; // Task<TResult> returns an object of type TResult, in this case int
		}
开发者ID:rpmobile,项目名称:mobile-samples,代码行数:33,代码来源:MainActivity.cs

示例8: GetRandomKitty

 static async Task<Bitmap> GetRandomKitty() {
     var httpClient = new HttpClient(new OkHttpNetworkHandler());
     httpClient.Timeout = TimeSpan.FromSeconds(10);
     var imageBytes = await httpClient.GetByteArrayAsync(kittyJpgUrl);
     Bitmap imageBitmap = await BitmapFactory.DecodeByteArrayAsync(imageBytes, 0, imageBytes.Length);
     return imageBitmap;
 }
开发者ID:patridge,项目名称:OkGlassFindACat,代码行数:7,代码来源:RandomKittyActivity.cs

示例9: saveImageToDisk

		private async Task saveImageToDisk(Articolo art) // async
		{
			HttpClient c = new HttpClient();
			c.BaseAddress =  new Uri(art.UrlImg);
			c.Timeout = new TimeSpan(0,0, 3);

			Byte[] imgByteArray = await c.GetByteArrayAsync ("");

			CancellationToken a = new CancellationToken();

			IFolder rootFolder = FileSystem.Current.LocalStorage;
  
			IFolder folder = await rootFolder.CreateFolderAsync("Immagini",
				CreationCollisionOption.OpenIfExists);

			var listaFilePerVerifica = await folder.GetFilesAsync (new CancellationToken ());

			var listafile = await folder.GetFilesAsync ();
			
			IFile file = await folder.CreateFileAsync(art.ImageFileName ,
				CreationCollisionOption.ReplaceExisting);
  
			// http://www.mallibone.com/post/storing-files-from-the-portable-class-library-(pcl)

			using (var fileHandler = await file.OpenAsync (FileAccess.ReadAndWrite)) {
				fileHandler.WriteAsync(imgByteArray, 0, imgByteArray.Length); // await
			}   
		}
开发者ID:maurocavallin,项目名称:CorsoXamarinGiugno2015,代码行数:28,代码来源:SecondaPagina.xaml.cs

示例10: GetFileStream

        protected Downloads.File GetFileStream(Downloads.File file)
        {
            using (var client = new HttpClient()) {

            try {
                var data = client.GetByteArrayAsync(file.DownloadUrl).Result;

                    if (data.Length > 0) {

                    var result = data.ToArray();
                    MemoryStream ms = new MemoryStream();
                    ms.Write(data, 0, data.Length);
                    ms.Position = 0;

                    file.FileStream = ms;
                    file.IsValidFile = true;
                    ms.Flush();

                    } else {
                        throw new Exception("Error: Unable to download file");
                    }
                } catch (AggregateException ex) {
                    //log error
                    ex.ToString();
              }
            }
              return file;
        }
开发者ID:sgauzel,项目名称:main,代码行数:28,代码来源:FileDownload.cs

示例11: SumPageSizesAsync

        private async Task SumPageSizesAsync()
        {
            // Declare an HttpClient object and increase the buffer size. The
            // default buffer size is 65,536.
            HttpClient client =
            new HttpClient() { MaxResponseContentBufferSize = 1000000 };

            // Make a list of web addresses.
            List<string> urlList = SetUpURLList();

            var total = 0;
            foreach (var url in urlList)
            {
                // GetURLContents returns the contents of url as a byte array.
                //byte[] urlContents = await GetURLContentsAsync(url);

                byte[] urlContents = await client.GetByteArrayAsync(url);   

                DisplayResults(url, urlContents);

                // Update the total.
                total += urlContents.Length;
            }

            // Display the total count for all of the web addresses.
            resultsTextBox.Text +=
                string.Format("\r\n\r\nTotal bytes returned:  {0}\r\n", total);
        }
开发者ID:dmuthami,项目名称:AsynchAwait,代码行数:28,代码来源:MainWindow.xaml.cs

示例12: UploadMessageAsync

 public void UploadMessageAsync()
 {
     var uri = this.UploadMessageHelperAsync().Result;
     var client = new HttpClient();
     var downloadedBody = client.GetByteArrayAsync(uri).Result;
     Assert.Equal(Valid.MessageContent, downloadedBody);
 }
开发者ID:AArnott,项目名称:IronPigeon,代码行数:7,代码来源:CloudBlobStorageProviderTestBase.cs

示例13: BitmapImageAsync

        public async Task<BitmapImage> BitmapImageAsync(string url)
        {
            Stream stream = null;
            HttpClient WebClient = new HttpClient();
            BitmapImage image = new BitmapImage();

            try
            {
                stream = new MemoryStream(await WebClient.GetByteArrayAsync(url));
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad; // here
                image.StreamSource = stream;
                image.EndInit();
                image.Freeze();
            }
            catch { }

            if (stream != null)
            {
                stream.Close(); stream.Dispose(); stream = null;
            }

            url = null; WebClient.CancelPendingRequests(); WebClient.Dispose(); WebClient = null;
            return image;
        }
开发者ID:korner-brazers,项目名称:VK-HashTag,代码行数:25,代码来源:DownloadImage.cs

示例14: Download

        public static async Task<byte[]> Download(string url)
        {
            Uri uri = new Uri(url);
            HttpClient httpClient = new HttpClient();

            return await httpClient.GetByteArrayAsync(uri);
        }
开发者ID:ptedeschi,项目名称:ImageCache,代码行数:7,代码来源:Net.cs

示例15: TortureAsync

		/// <summary>
		/// Concurrently requests the given <paramref name="target"/> <paramref name="requestCount"/> times.
		/// </summary>
		/// <param name="target">Uri to torture.</param>
		/// <param name="requestCount">Number of requests.</param>
		/// <param name="concurrentRequestLimit">Maximum number of concurrent requests.</param>
		public static async Task<TortureResult> TortureAsync(Uri target, Int64 requestCount, Int64 concurrentRequestLimit = 22)
		{
			Int64 bytesRead = 0;
			Stopwatch stopwatch = Stopwatch.StartNew();

			var pendingTasks = new List<Task<Byte[]>>();

			using (HttpClient client = new HttpClient())
			{
				for (Int64 index = 0; index < requestCount; index++)
				{
					Task<Byte[]> fetchTask = client.GetByteArrayAsync(target);
					pendingTasks.Add(fetchTask);

					if (pendingTasks.Count > concurrentRequestLimit)
					{
						foreach (var task in pendingTasks.ConsumeWhere(null))
						{
							Byte[] result = await task.ConfigureAwait(false);
							bytesRead += result.LongLength;
						}
					}
				}

				foreach (var task in pendingTasks.ConsumeWhere(null))
				{
					Byte[] result = await task.ConfigureAwait(false);
					bytesRead += result.LongLength;
				}
			}

			return new TortureResult { Target = target, RequestCount = requestCount, BytesRead = bytesRead, TimeElapsed = stopwatch.Elapsed };
		}
开发者ID:piedar,项目名称:Hushpuppy,代码行数:39,代码来源:HttpTorturer.cs


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