GetStreamAsync() публичный Метод

public GetStreamAsync ( Uri requestUri ) : Task
requestUri System.Uri
Результат Task
Пример #1
0
 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();
 }
Пример #2
0
        /// <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;
        }
Пример #3
0
        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;
        }
Пример #4
0
            public async Task Osu(IUserMessage umsg, string usr, [Remainder] string mode = null)
            {
                var channel = (ITextChannel)umsg.Channel;

                if (string.IsNullOrWhiteSpace(usr))
                    return;

                using (HttpClient http = new HttpClient())
                {
                    try
                    {
                        var m = 0;
                        if (!string.IsNullOrWhiteSpace(mode))
                        {
                            m = ResolveGameMode(mode);
                        }
                        http.AddFakeHeaders();
                        var res = await http.GetStreamAsync(new Uri($"http://lemmmy.pw/osusig/sig.php?uname={ usr }&flagshadow&xpbar&xpbarhex&pp=2&mode={m}")).ConfigureAwait(false);

                        MemoryStream ms = new MemoryStream();
                        res.CopyTo(ms);
                        ms.Position = 0;
                        await channel.SendFileAsync(ms, $"{usr}.png", $"🎧 **Profile Link: **https://osu.ppy.sh/u/{Uri.EscapeDataString(usr)}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        await channel.SendMessageAsync("💢 Failed retrieving osu signature :\\").ConfigureAwait(false);
                        _log.Warn(ex, "Osu command failed");
                    }
                }
            }
 private async Task<Stream> GetWebPageAsync() {
     
     using (var httpClient = new HttpClient()) {
         var stream = await httpClient.GetStreamAsync("http://localhost:9999");
         return stream;
     }
 }
Пример #6
0
 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;
     }
 }
        /// <summary>
        /// Authenticates a user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <param name="regionKey">The region key.</param>
        /// <returns>The async <see cref="Task"/>.</returns>
        public static async Task<CaasAccountDetails> Authenticate(string userName, string password, string regionKey)
        {
            var config = (ComputeConfigurationSection)ConfigurationManager.GetSection("compute");
            var credentials = new NetworkCredential(userName, password);
            var handler = new HttpClientHandler { Credentials = credentials };

            using (var client = new HttpClient(handler))
            {
                var region = config.Regions.Cast<RegionConfigurationElement>().FirstOrDefault(r => r.Key == regionKey);
                if (region == null)
                {
                    throw new ArgumentException($"The region with key '{regionKey}' does not exist in the app.config file.");
                }

                var responseSteam = await client.GetStreamAsync(region.BaseUrl + AuthUrl);
                var xdoc = XDocument.Load(responseSteam);
                XNamespace ns5 = "http://oec.api.opsource.net/schemas/directory";
                var orgId = xdoc.Root.Element(ns5 + "orgId").Value;
                return new CaasAccountDetails
                {
                    Credentials = new NetworkCredential(userName, password),
                    OrgId = orgId,
                    BaseUrl = region.BaseUrl,
                    Roles = xdoc.Root.Elements(ns5 + "roles").Elements(ns5 + "role").Elements(ns5 + "name").Select(e => e.Value).ToList()
                };
            }
        }
Пример #8
0
		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;
		}
Пример #9
0
        // <summary>
        // 板名の取得
        // </summary>
        public async Task setBbsNameAsync()
        {
            if (baseUrl != "")
            {
                using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
                {
                    bbsName = "";
                    // スレトップをすべて読み込み板名を取得
                    Stream stream = await httpClient.GetStreamAsync(baseUrl);

                    string baseHtml = "";
                    using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding(bbsEncoding)))
                    {
                        while (!reader.EndOfStream)
                        {
                            baseHtml += reader.ReadLine();
                        }
                    }
                    // タイトルタグを正規表現パース
                    string titleRegex   = "<title>(?<title>.*?)</title>";
                    Regex  retitleRegex = new Regex(titleRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    for (Match m = retitleRegex.Match(baseHtml); m.Success; m = m.NextMatch())
                    {
                        bbsName = m.Groups["title"].Value.Trim();
                    }
                }
            }
        }
Пример #10
0
        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);
        }
Пример #11
0
        // <summary>
        // 現在のスレタイの取得
        // </summary>
        public async Task setThreadNameAsync()
        {
            if (threadId != "")
            {
                using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
                {
                    threadName = "";
                    Regex titleRegex = new Regex(string.Format(threadTitleRegex, subjectDelimStrings), RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    // subject.txtを読み込み、スレタイを取得
                    Stream stream = await httpClient.GetStreamAsync(baseUrl + "subject.txt");

                    using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding(encoding)))
                    {
                        while (!reader.EndOfStream)
                        {
                            // 1行ごとに正規表現でスレタイを取得
                            var   subLine = reader.ReadLine();
                            Match m       = titleRegex.Match(subLine);
                            if (m.Success)
                            {
                                if (m.Groups["id"].Value == threadId)
                                {
                                    threadName = m.Groups["title"].Value;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #12
0
        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);
                    }
                });
        }
Пример #13
0
        public static void CallApi(TokenResponse response)
        {
            var client = new HttpClient();
            client.SetBearerToken(response.AccessToken);

            Console.WriteLine(client.GetStreamAsync("http://localhost:14869/test").Result);
        }
Пример #14
0
        public async Task HttpSample(bool secure)
        {
            var client = new System.Net.Http.HttpClient();

            viewController.HandlerType = typeof(HttpMessageInvoker).GetField("handler", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(client).GetType();
            viewController.RenderStream(await client.GetStreamAsync(secure ? "https://www.xamarin.com" : viewController.WisdomUrl));
        }
Пример #15
0
        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);
            }
        }
Пример #16
0
        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
        }
Пример #17
0
		public static async Task<Stream> GetImageStreamAsync(CameraModel camera)
		{
			var http = new HttpClient();
			http.DefaultRequestHeaders.Authorization = GetAuthenticationHeader(camera);

			return await http.GetStreamAsync(camera.Url);
		}
Пример #18
0
        public IAwaitableTransfer Load(Uri url, IProgress<ProgressValue> progress, CancellationToken cancellation)
        {
		    url = new Uri("https://ia700406.us.archive.org/28/items/GodSaveTheQueen_306/GodSaveTheQueen.ogg");
	        var task = Task.Run(async () =>
	        {
		        var client = new HttpClient();

		        var head = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url), cancellation);
		        var totalLength = (ulong) head.Content.Headers.ContentLength;
		        var source = await client.GetStreamAsync(url);

		        var folder = ApplicationData.Current.LocalFolder;
		        var file = await folder.CreateFileAsync(Path.GetFileName(url.AbsoluteUri), CreationCollisionOption.ReplaceExisting);

		        using (client)
		        using (var target = await file.OpenStreamForWriteAsync())
		        using (source)
		        {
			        var buffer = new byte[8192];
			        int bytesRead = 0;
			        while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellation)) > 0)
			        {
				        await target.WriteAsync(buffer, 0, bytesRead, cancellation);
				        progress.Report(new ProgressValue((ulong) target.Position, totalLength));
			        }
		        }
	        });

			return new StubDownloadAwaitableRequest(task, new Uri("\\" + Path.GetFileName(url.AbsoluteUri), UriKind.RelativeOrAbsolute));
        }
Пример #19
0
        public async Task UploadPdfAttachment()
        {
            IPlanGridApi client = PlanGridClient.Create();
            Stream payload = typeof(AttachmentTests).Assembly.GetManifestResourceStream("PlanGrid.Api.Tests.TestData.Sample.pdf");
            Attachment attachment = await client.UploadPdfAttachment(TestData.Project2Uid, "test name", payload, "test folder");

            Assert.AreEqual("test name", attachment.Name);
            Assert.AreEqual("test folder", attachment.Folder);
            Assert.AreEqual(TestData.ApiTestsUserUid, attachment.CreatedBy.Uid);
            Assert.AreNotEqual(attachment.CreatedAt, default(DateTime));

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

            Attachment retrievedAttachment = await client.GetAttachment(TestData.Project2Uid, attachment.Uid);
            Assert.IsFalse(retrievedAttachment.IsDeleted);
            await client.UpdateAttachment(TestData.Project2Uid, attachment.Uid, new AttachmentUpdate { Name = "new name", Folder = "new folder" });
            retrievedAttachment = await client.GetAttachment(TestData.Project2Uid, attachment.Uid);
            Assert.AreEqual("new name", retrievedAttachment.Name);
            Assert.AreEqual("new folder", retrievedAttachment.Folder);

            await client.RemoveAttachment(TestData.Project2Uid, attachment.Uid);
            Attachment removedAttachment = await client.GetAttachment(TestData.Project2Uid, attachment.Uid);
            Assert.IsTrue(removedAttachment.IsDeleted);
        }
        private static async Task<CurrentTzdbProvider> DownloadAsync()
        {
            using (var client = new HttpClient())
            {
                var latest = new Uri((await client.GetStringAsync("http://nodatime.org/tzdb/latest.txt")).TrimEnd());
                var fileName = latest.Segments.Last();
                var path = Path.Combine(Path.GetTempPath(), fileName);

                if (!File.Exists(path))
                {
                    using (var httpStream = await client.GetStreamAsync(latest))
                    using (var fileStream = File.Create(path))
                    {
                        await httpStream.CopyToAsync(fileStream);
                    }
                }

                using (var fileStream = File.OpenRead(path))
                {
                    var source = TzdbDateTimeZoneSource.FromStream(fileStream);
                    var provider = new DateTimeZoneCache(source);
                    return new CurrentTzdbProvider(provider, source.Aliases);
                }
            }
        }
        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;
        }
        public void LoadOnlinePermissions()
        {
            List<Permission> permissions;
            HttpClient client = new HttpClient();
            using (Stream s = client.GetStreamAsync("http://www.feed-the-beast.com/mods/json").Result)
            using (StreamReader sr = new StreamReader(s))
            using (JsonReader reader = new JsonTextReader(sr))
            {
                JsonSerializer serializer = new JsonSerializer();

                // read the json from a stream
                // json size doesn't matter because only a small piece is read at a time from the HTTP request
                permissions = serializer.Deserialize<List<Permission>>(reader);
            }
            _permissions = new List<Permission>();
            foreach (Permission p in permissions.Where(p => !String.IsNullOrWhiteSpace(p.privateStringPolicy) &&
                                                            !String.IsNullOrWhiteSpace(p.publicStringPolicy)))
            {
                PermissionPolicy pp;
                bool r = Enum.TryParse(p.privateStringPolicy, out pp);
                if (r)
                {
                    p.privatePolicy = pp;
                }
                r = Enum.TryParse(p.publicStringPolicy, out pp);
                if (r) p.publicPolicy = pp;
                p.privateStringPolicy = null;
                p.publicStringPolicy = null;
                _permissions.Add(p);
            }
            Save();
        }
Пример #23
0
        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);
        }
Пример #24
0
 /// <summary>
 /// Get the given attachmentid view as a stream
 /// </summary>
 /// <param name="attachmentId">attachmentid</param>
 /// <param name="viewId">view to get (default:original)</param>
 /// <returns>stream of attachment</returns>
 public Task<Stream> GetAttachmentStreamAsync(string attachmentId, string viewId = "original")
 {
     using (HttpClient client = new HttpClient())
     {
         return client.GetStreamAsync(GetAttachmentUri(attachmentId, viewId));
     }
 }
Пример #25
0
        // TODO: 一分ごとに画像と名前を取得する
        private async void GetBijinInfo()
        {
            var date = this.Current;
            getKawaii(this.path + this.Current.ToString("HHmm"));
            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);
            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);
                this.Image = bitmap;
            }

            var html = await client.GetStringAsync("http://www.bijint.com/" + Path + "/cache/" + date.ToString("HHmm") + ".html");
            var lines = html.Split('\n').Select(input => input.Trim()).Where(input => input != "\r" || input != "").ToList();
            var nameLineIndex = lines.IndexOf("<thead>") + 2;
            var nameLine = lines[nameLineIndex];
            var temp = nameLine.Substring(0, nameLine.Length - 5);
            var lastEnd = temp.LastIndexOf('>');
            this.Subtitle = temp.Substring(lastEnd + 1);


        }
Пример #26
0
        private async Task <string> SendMessage(string message)
        {
            String querys = "question=" + message;
            String url    = host + path;
            string reply;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }
            HttpClient client = new System.Net.Http.HttpClient();

            try
            {
                client.DefaultRequestHeaders.Add("Authorization", "APPCODE " + appcode);
                var reponse = await client.GetStreamAsync(url);

                var streamReader = new StreamReader(reponse, Encoding.UTF8);
                reply = streamReader.ReadToEnd();
            }catch (Exception err)
            {
                reply = err.Message;
            }
            finally
            {
                client.Dispose();
            }
            return(reply);
        }
        private async Task<Stream> GetWebPageAsync() {

            using (var httpClient = new HttpClient()) {
                var stream = await httpClient.GetStreamAsync("http://www.apress.com");
                return stream;
            }
        }
Пример #28
0
        private static async Task<string> DownloadAndExtractAsync(string url, string dir)
        {
            using (var client = new HttpClient())
            using (var httpStream = await client.GetStreamAsync(url))
            using (var reader = ReaderFactory.Open(httpStream))
            {
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);
                
                while (reader.MoveToNextEntry())
                {
                    var entry = reader.Entry;
                    if (entry.IsDirectory)
                        continue;

                    var targetPath = Path.Combine(dir, entry.FilePath.Replace('/', '\\'));
                    var targetDir = Path.GetDirectoryName(targetPath);
                    if (targetDir == null)
                        throw new InvalidOperationException();

                    if (!Directory.Exists(targetDir))
                        Directory.CreateDirectory(targetDir);

                    using (var stream = reader.OpenEntryStream())
                    using (var fs = File.Create(targetPath))
                    {
                        await stream.CopyToAsync(fs);
                    }

                }

                return dir;
            }
        }
Пример #29
0
 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.");
     }
 }
Пример #30
0
        //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;
        }
 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);
 }
Пример #32
0
        /// <summary>
        /// Downloads and copies the GetClrDbg.sh shell script to the remote machine.
        /// </summary>
        /// <param name="remoteDirectory">Location on the remote machine.</param>
        /// <param name="getclrdbgUri">URI of the GetClrDbg.sh script.</param>
        /// <returns>Full path of the location of GetClrDbg.sh on the remote machine.</returns>
        private async Task<string> DownloadAndCopyFileToRemote(string remoteDirectory, string getclrdbgUri)
        {
            string localFile = Path.GetTempFileName();
            string remoteFilePath = null;
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    using (var response = await httpClient.GetStreamAsync(getclrdbgUri))
                    {
                        using (TextReader textReader = new StreamReader(response))
                        {
                            using (Stream destinationStream = File.Create(localFile))
                            {
                                await response.CopyToAsync(destinationStream);
                            }
                        }
                    }
                }

                _launchOptions.UnixPort.MakeDirectory(remoteDirectory);
                remoteFilePath = remoteDirectory + Path.AltDirectorySeparatorChar + ShellScriptName;
                _launchOptions.UnixPort.CopyFile(localFile, remoteFilePath);
            }
            finally
            {
                if (File.Exists(localFile))
                {
                    File.Delete(localFile);
                }
            }

            return remoteFilePath;
        }
Пример #33
0
 /// <summary>
 /// Read stream
 /// </summary>
 /// <param name="url"></param>
 /// <returns></returns>
 public static Stream ReadStream(string url)
 {
     using (var client = new System.Net.Http.HttpClient())
     {
         /*
          * client.GetStreamAsync(url)
          * client.UseDefaultCredentials = true;
          * client.Proxy.Credentials = CredentialCache.DefaultCredentials;
          * client.Headers.Add("UserAgent", @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36");
          * client.Headers.Add("Sec-Fetch-Mode", @"no-cors");
          * client.Headers.Add("Referer", @"https://google.map4d.vn/");
          * client.Get
          * client.DownloadString(url);*/
         try
         {
             client.DefaultRequestHeaders.UserAgent.ParseAdd(@"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36");
             return(client.GetStreamAsync(url).Result);
         }
         catch (Exception e)
         {
             Console.WriteLine(e);
             return(null);
         }
     }
 }
        public async Task<string> GetDominantColor(string source)
        {
            var _client = new HttpClient();

            var imageData = await _client.GetStreamAsync(source);

            using (var bitmap = new Bitmap(imageData))
            {
                Equalize(bitmap);

                var colorsWithCount =
                    GetPixels(bitmap)
                        .GroupBy(color => color)
                        .Select(grp =>
                            new
                            {
                                Color = grp.Key,
                                Count = grp.Count()
                            })
                        .OrderByDescending(x => x.Count)
                        .Take(1); //take top color

                return ColorTranslator.ToHtml(colorsWithCount.First().Color);
            }
        }
Пример #35
0
        private static async Task CacheAll(HttpClient httpClient, DefaultLocalFileSystemHttpCacheProvider cacheProvider, IEnumerable<Uri> uris)
        {
            foreach (var uri in uris)
            {
                try
                {
                    if (!cacheProvider.IsCached(uri))
                    {
                        using (var stream = await httpClient.GetStreamAsync(uri))
                        {
                            cacheProvider.Cache(stream, uri);
                        }

                        Console.WriteLine(string.Format("[New]{0}", uri));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("[Cached]{0}", uri));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
        private async Task <Stream> GetStreamFromUrl(string url)
        {
            Stream imageData;

            using (var wc = new System.Net.Http.HttpClient())
                imageData = await wc.GetStreamAsync(url);

            return(imageData);
        }
Пример #37
0
        public async Task HttpSample(HttpMessageHandler handler = null)
        {
            System.Net.Http.HttpClient client = (handler == null) ?
                                                new System.Net.Http.HttpClient() :
                                                new System.Net.Http.HttpClient(handler);
            var stream = await client.GetStreamAsync(MainActivity.WisdomUrl);

            ad.RenderStream(stream);
        }
Пример #38
0
        /// <inheritdoc/>
        public virtual async Task <Stream> GetStreamAsync(string requestUri)
        {
            using var httpClientHandler = await CreateHttpClientHandlerAsync();

            using var httpClient = new System.Net.Http.HttpClient(httpClientHandler);
            httpClient.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue()
            {
                NoCache = true
            };
            return(await httpClient.GetStreamAsync(requestUri));
        }
Пример #39
0
        private async Task <string> FetchAsync(string url)
        {
            string jsonString;

            using (var httpClient = new System.Net.Http.HttpClient()) {
                var stream = await httpClient.GetStreamAsync(url);

                StreamReader reader = new StreamReader(stream);
                jsonString = reader.ReadToEnd();
            }

            return(jsonString);
        }
Пример #40
0
        // POST /api/sign
        public async Task <HttpResponseMessage> Post([FromBody] WebHookEvent payload)
        {
            if (payload.Payload.PackageIdentifier.EndsWith(ConfigurationManager.AppSettings["Signature:PackageIdSuffix"]))
            {
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    ReasonPhrase = "Package is already signed. "
                });
            }

            string tempPath = Path.GetTempFileName();

            try
            {
                // Download the package
                var httpClient    = new HttpClient();
                var packageStream = await httpClient.GetStreamAsync(payload.Payload.PackageDownloadUrl);

                using (var stream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    packageStream.CopyTo(stream);
                }

                // Sign the package
                PackageSigner signer = new PackageSigner();
                if (signer.SignPackage(tempPath, tempPath,
                                       System.Web.Hosting.HostingEnvironment.MapPath("~/" + ConfigurationManager.AppSettings["Signature:KeyFile"]),
                                       ConfigurationManager.AppSettings["Signature:KeyFilePassword"],
                                       payload.Payload.PackageIdentifier + ConfigurationManager.AppSettings["Signature:PackageIdSuffix"]))
                {
                    var server = new PackageServer(ConfigurationManager.AppSettings["Signature:NuGetFeedUrl"], "Signature/1.0");
                    server.PushPackage(ConfigurationManager.AppSettings["Signature:NuGetFeedApiKey"], new OptimizedZipPackage(tempPath), new FileInfo(tempPath).Length, 60 * 1000, true);
                    OptimizedZipPackage.PurgeCache();

                    return(new HttpResponseMessage(HttpStatusCode.Created)
                    {
                        ReasonPhrase = "Package has been signed."
                    });
                }
            }
            finally
            {
                File.Delete(tempPath);
            }

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                ReasonPhrase = "Package is already signed."
            });
        }
        public async Task SetIconAsync(string iconUrl)
        {
            var    iconDownloader     = new System.Net.Http.HttpClient();
            string tempFileTargetName = Path.GetTempFileName();

            using (var iconStream = await iconDownloader.GetStreamAsync(iconUrl).ConfigureAwait(false))
                using (var tempFileTarget = File.OpenWrite(tempFileTargetName))
                {
                    await iconStream.CopyToAsync(tempFileTarget).ConfigureAwait(false);
                }
            await Context.Client.CurrentUser.ModifyAsync(props => props.Avatar = new Image(tempFileTargetName)).ConfigureAwait(false);

            File.Delete(tempFileTargetName);
            await ReplyAsync("Avatar updated!").ConfigureAwait(false);
        }
Пример #42
0
        // <summary>
        // スレ一覧の取得
        // </summary>
        public async Task setSubjectsAsync()
        {
            if (baseUrl != "")
            {
                // subject.txtを読み込み、スレタイを取得
                using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
                {
                    Stream stream = await httpClient.GetStreamAsync(baseUrl + "subject.txt");

                    Regex titleRegex = new Regex(string.Format(threadTitleRegex, subjectDelimStrings), RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding(encoding)))
                    {
                        if (!reader.EndOfStream)
                        {
                            listSubjects.Clear();
                            var subjectOrder = 1;
                            while (!reader.EndOfStream)
                            {
                                // 1行ごとに正規表現でスレタイを取得
                                var   subLine = reader.ReadLine();
                                Match m       = titleRegex.Match(subLine);
                                if (m.Success)
                                {
                                    Subject bufSubject = new Subject();
                                    bufSubject.Order    = subjectOrder++;
                                    bufSubject.Title    = m.Groups["title"].Value;
                                    bufSubject.Url      = threadRootUrl + m.Groups["id"].Value + "/";
                                    bufSubject.ResCount = Int32.Parse(m.Groups["resCount"].Value);
                                    DateTime orgTime  = DateTime.Parse("1970/1/1 00:00:00");
                                    double   unixTime = (double)((DateTime.Now.ToFileTimeUtc() - orgTime.ToFileTimeUtc()) / 10000000) - System.Convert.ToDouble(m.Groups["id"].Value);
                                    if (unixTime > 0.01f)
                                    {
                                        double power = System.Convert.ToDouble(bufSubject.ResCount) / unixTime * 60.0f * 60.0f * 24.0f;
                                        bufSubject.Power = power;
                                    }
                                    listSubjects.Add(bufSubject);
                                    if (m.Groups["id"].Value == threadId)
                                    {
                                        threadName = m.Groups["title"].Value;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #43
0
        protected override async void OnAppearing()
        {
            base.OnAppearing();

            patients = await PatientLogic.GetPatients();

            HttpClientHandler httpClientHandler = new HttpClientHandler();

            httpClientHandler.ServerCertificateCustomValidationCallback =
                (message, cert, chain, errors) => { return(true); };

            var client = new System.Net.Http.HttpClient(httpClientHandler);

            System.IO.Stream imagestream = await client.GetStreamAsync(General.URL + "/Content/title.jpg");

            imageLogin.Source = ImageSource.FromStream(() => imagestream);
        }
Пример #44
0
        private async Task <(MemoryStream ms, string error)> DownloadDataAsync(string url)
        {
            var handler = new HttpClientHandler()
            {
                CookieContainer = new CookieContainer(),
            };

            if (this.IsLoggedIn)
            {
                handler.CookieContainer.Add(this.sessionCookie);
            }

            var client = new System.Net.Http.HttpClient(handler)
            {
                Timeout = TimeSpan.FromMilliseconds(connectionDetails.HttpContentRequestTimeout)
            };

            client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
            //client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");
            client.DefaultRequestHeaders.Add("Accept", "*/*");
            // TRICK: Empty value causes 500 error for 'http://connect.uthsc.edu/' during File Download
            client.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");

            // FIX: invalid SSL passing behavior
            // (Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            //ServicePointManager.SecurityProtocol =
            //    SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;

            try
            {
                using (var receiveStream = await client.GetStreamAsync(url))
                    using (var ms = new MemoryStream())
                    {
                        receiveStream.CopyTo(ms);
                        return(ms, null);
                    }
            }
            catch (Exception ex)
            {
                TraceTool.TraceException(ex);

                return(ms : null, error : ex.ToString());
            }
        }
Пример #45
0
        // <summary>
        // 現在のオブジェクトにスレッドURLが設定されているときに、datを取得してコレクションに追加する関数
        // 参考URL:http://www.studyinghttp.net/range
        // 上記URLを参考にdatの差分取得をする
        // Gzipの時はどうなる?
        // 差分取得について:http://sonson.jp/?p=541
        // </summary>
        public async Task getThreadLines()
        {
            if (datUrl != "")
            {
                using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
                {
                    //
                    Regex rdatRegex = new Regex(datRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    // subject.txtを読み込み、スレタイを取得
                    Stream stream = await httpClient.GetStreamAsync(datUrl);

                    using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding(encoding)))
                    {
                        DateTime dt;
                        int      idx = 1;
                        while (!reader.EndOfStream)
                        {
                            string sDatetime = "";
                            // 1行ごとに正規表現でthreadLineの各要素を取得
                            var   datLine = reader.ReadLine();
                            Match m       = rdatRegex.Match(datLine);
                            if (m.Success)
                            {
                                ThreadLine threadLine = new ThreadLine();
                                threadLine.Name = m.Groups["name"].Value;
                                threadLine.Url  = m.Groups["url"].Value;
                                if (Int32.Parse(m.Groups["date"].Value.Substring(0, 1)) > 7)
                                {
                                    sDatetime = "19" + m.Groups["date"].Value + " " + m.Groups["time"].Value;
                                }
                                else
                                {
                                    sDatetime = "20" + m.Groups["date"].Value + " " + m.Groups["time"].Value;
                                }
                                dt = DateTime.Parse(sDatetime);
                                threadLine.Date = DateTime.Parse(sDatetime);
                                threadLine.Body = stritpTag(HttpUtility.HtmlDecode(m.Groups["body"].Value.Replace("<br>", "\n")));
                                listTreadLines.Add(threadLine);
                            }
                            idx++;
                        }
                    }
                }
            }
        }
        public static async Task <string> FetchJSON(string url)
        {
            string            jsonString;
            HttpClientHandler handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };

            using (var httpClient = new System.Net.Http.HttpClient(handler))
            {
                Debug.WriteLine("urlll : " + url);
                var stream = await httpClient.GetStreamAsync(url);

                StreamReader reader = new StreamReader(stream);
                jsonString = reader.ReadToEnd();
            }
            return(jsonString);
        }
Пример #47
0
        public static void Main5()
        {
            using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
            {
                httpClient.Timeout = System.TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite);
                string           requestUri = "http://localhost:6797";
                System.IO.Stream stream     = httpClient.GetStreamAsync(requestUri).Result;

                using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                    {
                        //We are ready to read the stream
                        string currentLine = reader.ReadLine();
                    }
                }
            }
        }
Пример #48
0
        public async Task <ActionResult> Download(Guid id, string filename, string authToken)
        {
            using (var web = new System.Net.Http.HttpClient())
            {
                web.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken);

                var stream = await web.GetStreamAsync(WebConfigurationManager.AppSettings["ServiceUrl"] + "/documents/download?id=" + id.ToString("D"));

                var contentDisposition = new System.Net.Mime.ContentDisposition
                {
                    FileName = filename,
                    Inline   = false
                };
                Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

                return(File(stream, "application/octet-stream"));
            }
        }
Пример #49
0
 public Task <Stream> GetStreamAsync(Uri requestUri)
 {
     return(_builtInHttpClient.GetStreamAsync(requestUri));
 }
Пример #50
0
        public async Task HttpSample(string url)
        {
            var client = new System.Net.Http.HttpClient();

            ad.RenderStream(await client.GetStreamAsync(url));
        }
Пример #51
0
 public Task <Stream> GetStreamAsync(string requestUri)
 {
     return(_inner.GetStreamAsync(requestUri));
 }
        // <summary>
        // 現在のオブジェクトにスレッドURLが設定されているときに、datを取得してコレクションに追加する関数
        // 参考URL:http://www.studyinghttp.net/range
        // 上記URLを参考にdatの差分取得をする
        // Gzipの時はどうなる?
        // 差分取得について:http://sonson.jp/?p=541
        // 差分についてはしたらばとその他で取得方法違うようなので保留
        // そもそもストリームリーダーでエンコードしてる場合にサーバ側の保有バイト数が取れるかが謎
        // </summary>
        public async Task getThreadLines()
        {
            string lastModifiedFormat = "r";

            if (datUrl != "")
            {
                //clog("\n\n\n\n\n\n");
                HttpClientHandler handler = new HttpClientHandler();
                handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;
                using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(handler))
                {
                    string             ifModifiedSince = LastModified.ToString(lastModifiedFormat, CultureInfo.CreateSpecificCulture("en-US"));
                    HttpRequestMessage reqMsg          = new HttpRequestMessage();
                    bool clearThreadLines = false;
                    reqMsg.Headers.Add("Cache-Control", "no-cache");
                    reqMsg.Headers.Add("Accept", "text/plain");
                    //clog("現在のdatSize:" + datSize);
                    if (datSize > 0)
                    {
                        reqMsg.Headers.Add("Accept-Encoding", "identity");
                        if (isSetLastModified)
                        {
                            reqMsg.Headers.Add("If-Modified-Since", ifModifiedSince);
                        }
                        reqMsg.Headers.Add("Range", "bytes= " + (datSize - 1).ToString() + "-");
                    }
                    else
                    {
                        reqMsg.Headers.Add("Accept-Encoding", "gzip");
                    }
                    string reqUrl = datUrl;
                    if (datDiffRequest == "resNo")
                    {
                        reqUrl = datUrl + (listTreadLines.Count + 1).ToString() + "-";
                    }
                    httpClient.BaseAddress = new Uri(reqUrl);
                    //clog("現在のreqUrl:" + reqUrl);
                    Regex         rdatRegex = new Regex(datRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    Task <Stream> stream    = null;
                    ObservableCollection <ThreadLine> bufListthreadLines = new ObservableCollection <ThreadLine>();
                    Task <HttpResponseMessage>        response           = null;
                    try
                    {
                        await Task.Run(() =>
                        {
                            bool getDiff = false;
                            // リクエストヘッダを要求
                            response = httpClient.SendAsync(reqMsg);
                            //clog("要求リクエストヘッダ:" + reqMsg.Headers);
                            //clog("レスポンスコード:" + (Int32)response.Result.StatusCode);
                            //clog("レスポンスのリクエストヘッダ:" + response.Result.RequestMessage.Headers);
                            if (
                                response.Result.StatusCode == System.Net.HttpStatusCode.OK ||
                                response.Result.StatusCode == System.Net.HttpStatusCode.PartialContent ||
                                response.Result.StatusCode == System.Net.HttpStatusCode.RequestedRangeNotSatisfiable
                                )
                            {
                                httpClient.DefaultRequestHeaders.Add("Accept", "text/plain");
                                httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
                                // 実体のリクエスト発生経路
                                if (response.Result.StatusCode == System.Net.HttpStatusCode.OK && listTreadLines.Count == 0)
                                {
                                    // 全件
                                    httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
                                }
                                else if (response.Result.StatusCode == System.Net.HttpStatusCode.PartialContent || response.Result.StatusCode == System.Net.HttpStatusCode.OK)
                                {
                                    getDiff = true;
                                    // 差分
                                    httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "identity");
                                    //if (isSetLastModified) httpClient.DefaultRequestHeaders.Add("If-Modified-Since", ifModifiedSince);
                                    if (datDiffRequest == "range")
                                    {
                                        httpClient.DefaultRequestHeaders.Add("Range", "bytes= " + (datSize - 1).ToString() + "-");
                                    }
                                }
                                else if (response.Result.StatusCode == System.Net.HttpStatusCode.RequestedRangeNotSatisfiable)
                                {
                                    // 全件取得しなおし
                                    // 拾得済みdatサイズと格納済みdatをクリア
                                    //clog("データ破損、全件再取得");
                                    datSize          = 0;
                                    clearThreadLines = true;
                                    // 全件取得ヘッダ作成
                                    httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
                                }
                                // datに更新があればLast-Modifiedを更新
                                if (response.Result.Content.Headers.Contains("Last-Modified"))
                                {
                                    LastModified      = (DateTimeOffset)response.Result.Content.Headers.LastModified;
                                    isSetLastModified = true;
                                }
                                else
                                {
                                    LastModified      = new DateTimeOffset();
                                    isSetLastModified = false;
                                }
                                // 実体アクセス処理
                                stream = httpClient.GetStreamAsync(reqUrl);
                                // 受信データサイズ計算用Encodingインスタンス
                                Encoding enc = System.Text.Encoding.GetEncoding(encoding);
                                clog(encoding);
                                //enc = System.Text.Encoding.GetEncoding("UTF-8");
                                clog(httpClient.DefaultRequestHeaders.ToString());
                                using (StreamReader reader = new StreamReader(stream.Result, enc))
                                {
                                    //clog(DateTime.Now.ToString() + " : 取得開始");
                                    DateTime dt;
                                    int idx = 0;
                                    while (!reader.EndOfStream)
                                    {
                                        try
                                        {
                                            idx++;
                                            // 差分取得時の先頭1バイト判別
                                            if (idx == 1 && getDiff)
                                            {
                                                char[] charbuffer = new char[1];
                                                int result        = 0;
                                                result            = reader.Read(charbuffer, 0, 1);
                                                //clog("差分確認");
                                                int code = (int)charbuffer[0];
                                                if (code == 10 || code == 13)
                                                {
                                                    //clog("差分正常");
                                                    continue;
                                                }
                                                else
                                                {
                                                    clog("あぼーん検出");
                                                    datSize          = 0;
                                                    clearThreadLines = true;
                                                    break;
                                                }
                                            }
                                            ThreadLine threadLine = new ThreadLine();
                                            string sDatetime      = "";
                                            // 1行ごとに正規表現でthreadLineの各要素を取得
                                            string datLine = reader.ReadLine();
                                            datSize       += enc.GetByteCount(datLine) + enc.GetByteCount("\n");
                                            //clog("取得データ:" + datLine);
                                            //clog("取得データサイズ : " + datSize.ToString());
                                            //clog(datLine);
                                            Match m = rdatRegex.Match(datLine);
                                            if (m.Success)
                                            {
                                                threadLine.Name = m.Groups["name"].Value;
                                                threadLine.Url  = m.Groups["url"].Value;
                                                // わいわいなどは西暦が下2ケタなのでむりくり4ケタに修正
                                                if (Int32.Parse(m.Groups["date"].Value.Substring(0, 1)) >= 8)
                                                {
                                                    sDatetime = "19" + m.Groups["date"].Value + " " + m.Groups["time"].Value;
                                                }
                                                else
                                                {
                                                    sDatetime = "20" + m.Groups["date"].Value + " " + m.Groups["time"].Value;
                                                }
                                                dt = DateTime.Parse(sDatetime);
                                                threadLine.Date = DateTime.Parse(sDatetime);
                                                // 改行をhtmlタグから制御文字に変換、htmlエンコードされた特殊文字(&amp;等)をデコード、
                                                // HTMLタグを除去(>>1等のレス番指定やあっとちゃんねるずのURLにつくアンカータグ除去のため)
                                                // クラスに保存するデータは生データにする方針のため。再度アンカーなどを付けるのは各クライアントに任せる
                                                threadLine.Body = stritpTag(HttpUtility.HtmlDecode(m.Groups["body"].Value.Replace("<br>", "\n")));
                                            }
                                            else
                                            {
                                                // 削除されたレスと判断して空データをセット
                                                threadLine.Name = null;
                                                threadLine.Url  = null;
                                                threadLine.Date = new DateTime();
                                                threadLine.Body = null;
                                            }
                                            bufListthreadLines.Add(threadLine);
                                        }
                                        catch (Exception e)
                                        {
                                            clog("Webアクセスに失敗しました。" + e.Message);
                                            throw new NichanBbsConnectorException("Webアクセスに失敗しました。" + e.Message + e.StackTrace);
                                        }
                                        finally
                                        {
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (response.Result.StatusCode == System.Net.HttpStatusCode.NotModified)
                                {
                                    // 変更なし
                                    // 何もせず非同期スレッドを終了
                                }
                                else
                                {
                                    // その他HTTPレスポンスエラーの処理
                                    throw new NichanBbsConnectorException((Int32)response.Result.StatusCode + " [" + response.Result.StatusCode.ToString() + "] Webアクセスに失敗しました。");
                                }
                            }
                        });
                    }
                    catch (Exception e)
                    {
                        clog("非同期中に何らかのエラーが発生しました。" + e.Message + e.StackTrace);
                        throw new NichanBbsConnectorException("非同期中に何らかのエラーが発生しました。" + e.Message + e.StackTrace);
                    }
                    //Etag  = response.Result.Content.Headers.GetValues("Etag").ToString();
                    //clog("datSize:" + datSize);
                    //System.Console.WriteLine(DateTime.Now.ToString() + " : 取得完了" + bufListthreadLines.Count.ToString() + "件");
                    if (clearThreadLines)
                    {
                        listTreadLines.Clear();
                    }
                    foreach (ThreadLine res in bufListthreadLines)
                    {
                        listTreadLines.Add(res);
                    }
                }
            }
        }
Пример #53
0
        public async Task HttpSample()
        {
            var client = new System.Net.Http.HttpClient(new CFNetworkHandler());

            ad.RenderStream(await client.GetStreamAsync(Application.WisdomUrl));
        }
Пример #54
0
        public async Task HttpSample(HttpMessageHandler handler)
        {
            var client = new System.Net.Http.HttpClient(handler);

            ad.RenderStream(await client.GetStreamAsync(Application.WisdomUrl));
        }
Пример #55
0
        static async Task MainInner(string version)
        {
            Console.WriteLine($"Creating package for version {version}");

            // Clean up any previous download
            string packageDirectory = $"package-{version}";
            string sourceDirectory  = $"libusb-win32-bin-{version}";
            string packagePath      = $"libusbwin32-driver-{version}.nupkg";

            if (Directory.Exists(packageDirectory))
            {
                Directory.Delete(packageDirectory, true);
            }

            if (Directory.Exists(sourceDirectory))
            {
                Directory.Delete(sourceDirectory, true);
            }

            if (File.Exists(packagePath))
            {
                File.Delete(packagePath);
            }

            // Download and extract the latest version
            var client = new System.Net.Http.HttpClient();

            for (int i = 0; i < 3; i++)
            {
                // Not all SF mirrors may still hold the older versions
                try
                {
                    using (Stream stream = await client.GetStreamAsync($"http://downloads.sourceforge.net/project/libusb-win32/libusb-win32-releases/{version}/libusb-win32-bin-{version}.zip"))
                        using (ZipArchive archive = new ZipArchive(stream))
                        {
                            archive.ExtractToDirectory(".");
                        }
                }
                catch (Exception ex)
                {
                }

                break;
            }

            // Create the package folder
            Directory.CreateDirectory(packageDirectory);
            Directory.CreateDirectory($@"{packageDirectory}\amd64");
            Directory.CreateDirectory($@"{packageDirectory}\x86");

            // Copy the files
            File.Copy($@"{sourceDirectory}\bin\amd64\libusb0.dll", $@"{packageDirectory}\amd64\libusb0.dll");
            File.Copy($@"{sourceDirectory}\bin\amd64\libusb0.sys", $@"{packageDirectory}\amd64\libusb0.sys");

            File.Copy($@"{sourceDirectory}\bin\x86\libusb0_x86.dll", $@"{packageDirectory}\x86\libusb0_x86.dll");
            File.Copy($@"{sourceDirectory}\bin\x86\libusb0.sys", $@"{packageDirectory}\x86\libusb0.sys");

            // Generate the .nuspec file
            string packageTemplate = File.ReadAllText("libusbwin32-driver.nuspec");
            string nugetPackage    = packageTemplate.Replace("{Version}", version);

            nugetPackage = nugetPackage.Replace("{Dir}", packageDirectory);

            File.WriteAllText(packagePath, nugetPackage);

            PackageBuilder builder = new PackageBuilder(packagePath, null, false);

            using (Stream stream = File.Open(packagePath, FileMode.Create, FileAccess.ReadWrite))
            {
                builder.Save(stream);
            }
        }
Пример #56
0
 public async Task <Stream> GetStreamAsync(string url)
 => await _client.GetStreamAsync(url).ConfigureAwait(false);