private async void Button_Click(object sender, RoutedEventArgs e) { if (CountryPhoneCode.SelectedItem != null) { var _id = Guid.NewGuid().ToString("N"); var _countryPhoneCode = (CountryPhoneCode.SelectedItem as Country).PhoneCode; var _countryName = (CountryPhoneCode.SelectedItem as Country).CountryName; var _name = FullName.Text; var _phoneNumber = PhoneNumber.Text; var _password = Password.Password; var client = new HttpClient() { BaseAddress = new Uri("http://yochat.azurewebsites.net/chat/") }; var json = await client.GetStringAsync("createuser?id=" + _id + "&fullName=" + _name + "&password="******"&phoneNumber=" + _phoneNumber + "&countryPhoneCode=" + _countryPhoneCode); var serializer = new DataContractJsonSerializer(typeof(User)); var ms = new MemoryStream(); var user = serializer.ReadObject(ms) as User; Frame.Navigate(typeof(MainPage), user); } else { MessageDialog dialog = new MessageDialog("Lütfen Ülkenizi Seçiniz!"); await dialog.ShowAsync(); } }
private static async Task<string> GetVideoLink(string link) { var httpClient = new HttpClient(); var response = await httpClient.GetStringAsync(link); var doc = new HtmlDocument(); doc.LoadHtml(response); var iframeLink = doc.DocumentNode.Descendants("body"). First(). Descendants("iframe"). First(). Attributes["src"]. Value; response = await httpClient.GetStringAsync(iframeLink); doc.LoadHtml(response); var videoLink = response.Split('\"'). Where(part => part.Contains(".mp4") && part.StartsWith(@"http://")). FirstOrDefault(); return videoLink; }
/// <summary> /// 非同步刷新最新資訊 /// </summary> /// <returns></returns> public async Task RefreshAsync() { HttpClient client = new HttpClient(); HtmlDocument HTMLDoc = new HtmlDocument(); HTMLDoc.LoadHtml(await client.GetStringAsync(DataSource)); var script = HTMLDoc.DocumentNode.Descendants("script") .Where(x => x.InnerHtml?.Length > 0).Select(x => x.InnerHtml).ToArray(); var tempAry = script.First() .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select((x, i) => new { index = i, item = x }) .GroupBy(x => Math.Floor(x.index / 4.0)); this.LastPassed = null; this.Delay = new TimeSpan(); foreach (var item in tempAry) { string[] temp = item.Select(x=>x.item).ToArray(); if(temp[3] == "TRSearchResult.push('x')") { this.LastPassed = await Station.GetStationByNameAsync( innerString(temp[0],"'","'") ); } } var time = new TimeSpan(0, int.Parse(innerString(script.Last(), "=", ";")),0); this.Delay= time; }
private async static Task GetWebSiteContent() { HttpClient client = new HttpClient(); try { var result = await client.GetStringAsync("http://www.firstcrazydeveloper.com"); WriteLine(result); } catch (Exception exception) { try { //This asynchronous request will run if the first request failed. var result = await client.GetStringAsync("http://www.codingalmanac.com"); WriteLine(result); } catch { WriteLine("Entered Catch Block"); } finally { WriteLine("Entered Finally Block"); } } }
public static async Task<Exception> CheckAuth(string id, string pass,SQLiteConnection connection) { pass = base64Encode (pass); var httpClient = new HttpClient (); Exception error; httpClient.Timeout = TimeSpan.FromSeconds (20); string contents; Task<string> contentsTask = httpClient.GetStringAsync ("http://www.schoolapi.somee.com/dangnhap/"+id+"/"+pass); try { contents = await contentsTask; } catch(Exception e) { error =new Exception("Xảy Ra Lỗi Trong Quá Trình Kết Nối Server"); return error; } if (contents.Contains ("false")) { error=new Exception("Mã Sinh Viên Hoặc Mật Khẩu Không Đúng"); return error; } User usr = new User (); usr.Password = pass; usr.Id = id; Task<string> contentNameTask = httpClient.GetStringAsync ("http://www.schoolapi.somee.com/user/" + id); contents=await contentNameTask; XDocument doc = XDocument.Parse (contents); usr.Hoten= doc.Root.Elements().ElementAt(0).Elements().ElementAt(1).Value.ToString(); int i = AddUser (connection, usr); return null; }
private static async Task MainAsync() { // configure var settings = new TorSharpSettings { ZippedToolsDirectory = Path.Combine(Path.GetTempPath(), "TorZipped"), ExtractedToolsDirectory = Path.Combine(Path.GetTempPath(), "TorExtracted"), PrivoxyPort = 1337, TorSocksPort = 1338, TorControlPort = 1339, TorControlPassword = "******", ToolRunnerType = ToolRunnerType.Simple }; // download tools await new TorSharpToolFetcher(settings, new HttpClient()).FetchAsync(); // execute var proxy = new TorSharpProxy(settings); var handler = new HttpClientHandler { Proxy = new WebProxy(new Uri("http://localhost:" + settings.PrivoxyPort)) }; var httpClient = new HttpClient(handler); await proxy.ConfigureAndStartAsync(); Console.WriteLine(await httpClient.GetStringAsync("http://icanhazip.com")); await proxy.GetNewIdentityAsync(); Console.WriteLine(await httpClient.GetStringAsync("http://icanhazip.com")); proxy.Stop(); }
public async Task<string> GetLink(string tvShow, int season, int episode, params string[] exclude) { var encodedString = WebUtility.UrlEncode(tvShow); var httpClient = new HttpClient(); var response = await httpClient.GetStringAsync(string.Format(LetMeWatchThisQuery, LetMeWatchThis, encodedString)); IList<string> results = GetQueryResults(response); var first = results[0]; response = await httpClient.GetStringAsync(LetMeWatchThis + first); foreach (var link in await GetEpisodeLinks(response, season, episode)) try { var videoLink = await GetVideoLink(link); if (videoLink == null || exclude.Contains(videoLink)) continue; return videoLink; } catch { } return null; }
public async Task<string> GetLink(string tvShow, int season, int episode, params string[] exclude) { tvShow = tvShow.Replace("&", "and"); var encodedString = WebUtility.UrlEncode(tvShow); var httpClient = new HttpClient(); var response = await httpClient.GetStringAsync(string.Format(FreeTvQuery, FreeTv, encodedString)); IList<string> results = GetQueryResults(response); var first = results[0]; response = await httpClient.GetStringAsync(string.Format(FreeTv + first + FreeTvSeason, season)); foreach (var link in GetEpisodeLinks(response, episode)) try { var videoLink = await GetVideoLink(link); if (videoLink == null) continue; return videoLink; } catch { } return null; }
static async Task Download(string id, string path) { var index = new Uri(string.Format("https://api.nuget.org/v3/registration1/{0}/index.json", id.ToLowerInvariant())); HttpClient client = new HttpClient(); string jsonIndex = await client.GetStringAsync(index); JObject objIndex = JObject.Parse(jsonIndex); File.WriteAllText(path + "index.json", jsonIndex); foreach (var item in objIndex["items"]) { string pageUri = item["@id"].ToString(); Console.WriteLine("{0}", pageUri); string jsonPage = await client.GetStringAsync(pageUri); JObject jsonObj = JObject.Parse(jsonPage); var lower = item["lower"]; var upper = item["upper"]; string filename = string.Format("{0}_{1}_{2}.json", id.ToLowerInvariant(), lower, upper); File.WriteAllText(path + filename, jsonPage); } }
public static async Task<IEnumerable<FileInfo>> LibraryInfoAsync (string Category) { string result = null; IEnumerable<FileInfo> data; var client = new HttpClient (); try { result = await client.GetStringAsync (WebApiUrls.Library); data = JsonConvert.DeserializeObject<IEnumerable<FileInfo>> (result).ToList (); //return data.Where (i => i.Category == Category).AsEnumerable (); } catch { result = await client.GetStringAsync (WebApiUrls.Library); data = JsonConvert.DeserializeObject<IEnumerable<FileInfo>> (result).ToList (); //return data.Where (i => i.Category == Category).AsEnumerable (); } if (Category != "All") { data = data.Where (i => i.Category == Category).AsEnumerable (); } else { data = data.Where (i => i.Category != "newsletter").AsEnumerable (); } return data; }
public async Task Load() { var cli = new HttpClient(); var res = await cli.GetStringAsync("http://api.openweathermap.org/data/2.5/weather?q=Moscow&mode=json&units=metric&APPID=" + AppID); dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(res); Temperature = x.main.temp; Pic = new BitmapImage(new Uri($"http://openweathermap.org/img/w/{x.weather[0].icon}.png")); if (PropertyChanged!=null) { PropertyChanged(this,new PropertyChangedEventArgs("Temperature")); PropertyChanged(this,new PropertyChangedEventArgs("Pic")); } res = await cli.GetStringAsync("http://api.openweathermap.org/data/2.5/forecast/daily?q=Moscow&mode=json&units=metric&cnt=7&APPID="+AppID); x = Newtonsoft.Json.JsonConvert.DeserializeObject(res); foreach (var z in x.list) { Forecast.Add(new WeatherRecord() { When = Convert((long)z.dt), Temp = z.temp.day, Pressure = z.pressure, Humidity = z.humidity, Icon = new BitmapImage(new Uri($"http://openweathermap.org/img/w/{z.weather[0].icon}.png")) }); } }
public async Task ExecuteMultipleRequestsInParallel() { HttpClient client = new HttpClient(); Task microsoft = client.GetStringAsync("http://www.microsoft.com"); Task msdn = client.GetStringAsync("http://msdn.microsoft.com"); Task blogs = client.GetStringAsync("http://blogs.msdn.com/"); await Task.WhenAll(microsoft, msdn, blogs); }
private async void Button_Click(object sender, RoutedEventArgs e) { var cli = new HttpClient(); await cli.GetStringAsync($"{uri}/User/{uname.Text}"); var res = await cli.GetStringAsync($"{uri}/User"); var ulist = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(res); lb.ItemsSource = ulist; }
public async Task ExecuteMultipleRequests() { var client = new HttpClient(); string microsoft = await client.GetStringAsync("http://www.microsoft.com"); string msdn = await client.GetStringAsync("http://msdn.microsoft.com"); string blogs = await client.GetStringAsync("http://blogs.msdn.com/"); }
/// <summary> /// 公众号获取JS-SDK /// <see cref="https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html" /> /// </summary> /// <param name="token"></param> /// <returns></returns> public async Task <TicketResult> GetTicket(string token) { var strResponse = await _client.GetStringAsync($"cgi-bin/ticket/getticket?access_token={token}&type=jsapi"); var jsonReuslt = strResponse.TryConvert <TicketResult>(); return(await Task.FromResult(jsonReuslt)); }
public void GetString_RelativeUri() { var client = new HttpClient (); client.BaseAddress = new Uri ("http://en.wikipedia.org/wiki/"); var uri = new Uri ("Computer", UriKind.Relative); Assert.That (client.GetStringAsync (uri).Result != null); Assert.That (client.GetStringAsync ("Computer").Result != null); }
static void Ex1() { System.Net.Http.HttpClientHandler handler = new HttpClientHandler(); handler.UseProxy = false; System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(handler); System.Threading.Tasks.Task.Run(async() => { Console.WriteLine(await httpClient.GetStringAsync("http://www.linqpad.net")); Console.WriteLine(await httpClient.GetStringAsync("http://www.albahari.com")); }); }
public async Task<string> ExecuteMultipleRequestsInParallel () { HttpClient client = new HttpClient (); Task<string> one = client.GetStringAsync ("http://www.google.co.uk/"); Task<string> two = client.GetStringAsync ("http://monodevelop.com/"); await Task.WhenAll (one, two); return one.Result + two.Result; }
public static async Task ExecuteMiltiplerequests() { HttpClient client = new HttpClient(); string microsoft = await client.GetStringAsync("http://www.microsoft.com"); Console.WriteLine(microsoft); string msdn = await client.GetStringAsync("http://msdn.microsoft.com"); Console.WriteLine(msdn); string blogs = await client.GetStringAsync("http://blogs.msdn.com"); Console.WriteLine(blogs); }
public async Task EndToEnd_SingleThreadedTwoGetRequests_Success() { OwinHttpListener listener = CreateServer(env => Task.FromResult(0), HttpServerAddress); using (listener) { var client = new HttpClient(); string result = await client.GetStringAsync(HttpClientAddress); Assert.Equal(string.Empty, result); result = await client.GetStringAsync(HttpClientAddress); Assert.Equal(string.Empty, result); } }
static async Task<TimeSpan> RunTest(string url, int concurrentConnections) { var sw = new Stopwatch(); var client = new HttpClient(); await client.GetStringAsync(url); // warmup sw.Start(); await Task.WhenAll(Enumerable.Range(0, concurrentConnections).Select(i => client.GetStringAsync(url))); sw.Stop(); return sw.Elapsed; }
/// <summary> /// 根据服务器制定head的编码得到Html /// http://stackoverflow.com/questions/11018813/encoding-with-http-client-in-net-4-5 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string DownLoadHtml(string url) { var http = new HttpClient(); try { return http.GetStringAsync(url).Result; } catch (Exception) { return http.GetStringAsync(url).Result; } }
public async Task GetSubFolderIndex() { var webClient = new HttpClient(); var html = await webClient.GetStringAsync(WebServerUrl + "sub/"); Assert.AreEqual(Resources.SubIndex, html, "Same content index.html"); html = await webClient.GetStringAsync(WebServerUrl + "sub"); Assert.AreEqual(Resources.SubIndex, html, "Same content index.html without trailing"); }
public void EmptyAppAnd2Requests() { var listener = CreateServer(env => Task.Delay(0)); using (listener) { var client = new HttpClient(); string result = client.GetStringAsync(HttpClientAddress).Result; Assert.Equal("", result); result = client.GetStringAsync(HttpClientAddress).Result; Assert.Equal("", result); } }
internal async Task <Tuple <bool, string> > TryGetUri(string commandUri) { var connectAttemptCount = 0; Tuple <bool, string> result; while (true) { try { string strResult = null; LOGGER.Log(Level.Verbose, "Try url [" + commandUri + "] connectAttemptCount " + connectAttemptCount + "."); strResult = await _client.GetStringAsync(commandUri); result = CommandSucceeded(strResult); LOGGER.Log(Level.Verbose, "Connection succeeded. connectAttemptCount was " + connectAttemptCount + "."); break; } catch (HttpRequestException httpRequestException) { if (!ShouldRetry(httpRequestException)) { LOGGER.Log(Level.Error, commandUri + " exception " + httpRequestException.Message + "\n" + httpRequestException.StackTrace); result = CommandFailed(httpRequestException.Message); LOGGER.Log(Level.Warning, "Connection failed. connectAttemptCount was " + connectAttemptCount + "."); break; } } catch (Exception ex) { LOGGER.Log(Level.Error, commandUri + " exception " + ex.Message + "\n" + ex.StackTrace); result = CommandFailed(ex.Message); LOGGER.Log(Level.Warning, "Connection failed. connectAttemptCount was " + connectAttemptCount + "."); break; } ++connectAttemptCount; if (connectAttemptCount >= MaxConnectAttemptCount) { result = CommandFailed("Could not connect to " + commandUri + " after " + MaxConnectAttemptCount.ToString() + "attempts."); LOGGER.Log(Level.Warning, "Connection failed. connectAttemptCount was " + connectAttemptCount + "."); break; } Thread.Sleep(MilliSecondsToWaitBeforeNextConnectAttempt); } return(result); }
//http://api.fixer.io/2015-08-08?base=NZD async void getData(string Currency) { // Let the user know something is happening so that they don't think the // app has frozen. string error=""; // We need a try/catch wrapped around our API resquest just incase an error occurs // while calling the weather API. If an error does occur the code inside the catch // statement is called, otherwise the app skips it and continues with the code. // Without a try/catch, if an error does occur the app would not know how to handle it // resulting in the app crashing. A try/catch prevents the app from crashing and can be // used to inform the user what went wrong. try { // Initializing HTTPClient. HttpClient client = new HttpClient(); // Call data from api for today. string x = await client.GetStringAsync(new Uri("http://api.fixer.io/latest?base=NZD")); // Bind data rootObject1 = JsonConvert.DeserializeObject<CurrClass.RootObject>(x); setCurrentValue(); //30 days ago DateTime newDate = DateTime.Now; string Date30Str = newDate.AddDays(-30).ToString("yyyy-MM-dd"); x = await client.GetStringAsync(new Uri("http://api.fixer.io/"+ Date30Str +"?base=" + Currency)); rootObject2 = JsonConvert.DeserializeObject<CurrClass.RootObject>(x); set30Value(); //360 days ago string Date360Str = newDate.AddYears(-1).ToString("yyyy-MM-dd"); x = await client.GetStringAsync(new Uri("http://api.fixer.io/" + Date360Str + "?base=NZD")); rootObject3 = JsonConvert.DeserializeObject<CurrClass.RootObject>(x); set360Value(); } catch (Exception ex) { // Assigning the string error to whatever exception occured. error = ex.Message; } // Checks if the error string is not set to null. if (error != "") { // Displays a message box informing the user if an error occured. MessageBox.Show("Error: " + error); } }
public override async Task ProcessRequestAsync(HttpContext context) { using (var client = new HttpClient()) { var twitter = await client.GetStringAsync("http://twitter.com"); context.Response.Write(twitter); var flushTask = context.Response.FlushAsync(); var bingTask = client.GetStringAsync("http://bing.com"); await Task.WhenAll(flushTask, bingTask); context.Response.Write(bingTask.Result); } }
protected dynamic request(string uri) { System.Net.Http.HttpClient http = new System.Net.Http.HttpClient(); string json = http.GetStringAsync(uri).GetAwaiter().GetResult(); return(JsonConvert.DeserializeObject <dynamic>(json)); }
private async Task<string> GetFileAsync(string url) { using (var client = new HttpClient()) { return await client.GetStringAsync(url); } }
public void LoadInfoFromPartialUrlWithHttp() { var path = RootUrl; TypefaceReader reader; StreamLoader loader; using (var http = new System.Net.Http.HttpClient()) { using (reader = new TypefaceReader(new Uri(path), http)) { Assert.IsNotNull(reader.Loader.Client, "The loader SHOULD have a client as it was provided"); path = UrlPath; var info = reader.ReadTypeface(path); ValidateHelvetica.AssertInfo(info, path, 7); //check http is set Assert.IsNotNull(reader.Loader.Client, "The loader should STILL have a client as it was provided"); Assert.IsFalse(reader.Loader.OwnsClient, "The loader should NOT own the client as it was provided"); loader = reader.Loader; } //check clean up Assert.IsNull(reader.Loader, "The readers loader should have been set to null"); Assert.IsNull(loader.Client, "The loaders http should have been set to null, but not disposed"); //Simple check to make sure we are still able to use the http client var data = http.GetStringAsync(CheckAliveUrl).Result; Assert.IsNotNull(data); Assert.IsTrue(data.StartsWith("<Project ")); } }
private static string CallService(string token) { var client = new HttpClient(); client.SetBearerToken(token); var response = client.GetStringAsync(new Uri("http://localhost:2727/api/identity")).Result; return response; }
public static async Task <string> MakeRequestAndLogFailures() { //The implementation details for adding await support inside catch and finally //clauses ensure that the behavior is consistent with the behavior for synchronous code. //When code executed in a catch or finally clause throws, execution looks for a suitable //catch clause in the next surrounding block.If there was a current exception, that exception //is lost.The same happens with awaited expressions in catch and finally clauses: //a suitable catch is searched for, and the current exception, if any, is lost. await LogMethodEntrance(); var client = new System.Net.Http.HttpClient(); var streamTask = client.GetStringAsync("https://localHost:10000"); try { var responseText = await streamTask; return(responseText); } catch (System.Net.Http.HttpRequestException e) when(e.Message.Contains("301")) { await LogError("Recovered from redirect", e); return("Site Moved"); } finally { await LogMethodExit(); client.Dispose(); } }
/// <summary> /// Retrieves the list of K2 workflow tasks for the authenticated user /// </summary> /// <param name="WebClient">HttpClient set up with authentication credentials</param> /// <param name="TasksEndpointURI">the URI of the workflow tasks endpoint (e.g. https://k2.denallix.com/api/workflow/v1/tasks) </param> public void RetrieveWorklist(System.Net.Http.HttpClient WebClient, string TasksEndpointURI) { Console.WriteLine("**RetrieveWorklist starting**"); //retrieve the authenticated user's task list as JSON string response = WebClient.GetStringAsync(TasksEndpointURI).Result; //process the JSON response using a JSON deserializer. //In this case the built-in .NET DataContractSerializer class (you may want to use JSON.NET instead) //instantiate the DataContract used to parse the returned JSON worklist WorkflowRestAPISamples.Tasks_TasklistContract.K2TaskList tasklist = new WorkflowRestAPISamples.Tasks_TasklistContract.K2TaskList(); //Deserialize the response into the tasklist object, using the K2TaskList data contract. using (System.IO.MemoryStream memstream = new MemoryStream(Encoding.UTF8.GetBytes(response))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new DataContractJsonSerializer(tasklist.GetType()); memstream.Position = 0; tasklist = (WorkflowRestAPISamples.Tasks_TasklistContract.K2TaskList)serializer.ReadObject(memstream); } //do something with the collection of tasks in the retrieved task list foreach (WorkflowRestAPISamples.Tasks_TasklistContract.K2TaskListTask task in tasklist.K2Tasks) { Console.WriteLine("Folio: " + task.WorkflowInstanceFolio); Console.WriteLine("Workflow Name: " + task.WorkflowName); Console.WriteLine("Step: " + task.ActivityName); Console.WriteLine("Task Form URL: " + task.FormURL); Console.WriteLine("Serial Number: " + task.SerialNumber); Console.WriteLine("**************"); } Console.WriteLine("**RetrieveWorklist done**"); //wait for user input to continue Console.ReadLine(); }
public ModuleSafeties() : base("/doorbell") { // 转發安防設定 Get["/guard", true] = async(parameters, ct) => { string DeviceId = this.Request.Query["ro"]; string mode = this.Request.Query["mode"]; Match m = Regex.Match(DeviceId, @"^\w{2}-\w{2}-\w{2}-\w{2}-\w{2}-\w{2}$"); if (m.Length == 0) { return(HttpStatusCode.BadRequest); // illigal Device address format } DeviceId = m.Value; using (var db = new ICMDBContext()) { var Device = (from d in db.Devices where d.roomid == DeviceId select d).FirstOrDefault(); if (Device != null) { string uri = string.Format("http://{0}/guard?ro={1}&mode={2}", Device.ip, DeviceId, mode); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); try { var response = await client.GetStringAsync(uri); return(response); } catch (Exception) { } } } return("FAIL"); }; }
public void FailLoadInfoWithHttp() { var path = RootUrl; TypefaceReader reader; StreamLoader loader; using (var http = new System.Net.Http.HttpClient()) { using (reader = new TypefaceReader(http)) { Assert.IsNotNull(reader.Loader.Client, "The loader SHOULD have a client as it was provided"); path += FailingUrlPath; Assert.ThrowsException <AggregateException>(() => { var info = reader.ReadTypeface(path); }); //check http is set Assert.IsNotNull(reader.Loader.Client, "The loader should STILL have a client as it was provided"); Assert.IsFalse(reader.Loader.OwnsClient, "The loader should NOT own the client as it was provided"); loader = reader.Loader; } //check clean up Assert.IsNull(reader.Loader, "The readers loader should have been set to null"); Assert.IsNull(loader.Client, "The loaders http should have been set to null, but not disposed"); //Simple check to make sure we are still able to use the http client var data = http.GetStringAsync(CheckAliveUrl).Result; Assert.IsNotNull(data); Assert.IsTrue(data.StartsWith("<Project ")); } }
/// <summary> /// 获取网页HTML内容 /// </summary> /// <param name="url">URL地址</param> /// <returns></returns> public static string Get(string url) { string respHTML = ""; try { //var url = @"https://xxx.xxx.xxx.xxx:xxxx/xxx-web/services/xxxx?wsdl"; var handler = new HttpClientHandler { //ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true, //ClientCertificateOptions = ClientCertificateOption.Manual, //ClientCertificates ={ // new X509Certificate2(@"E:\cert\rootTrust.cer","11111111"), // new X509Certificate2(@"E:\cert\middleTrust.cer","11111111"), // new X509Certificate2(@"E:\cert\wskey.pfx","ws654321") //} AllowAutoRedirect = true, UseProxy = false, Proxy = null, //UseCookies = true, //CookieContainer = cookies, ClientCertificateOptions = ClientCertificateOption.Automatic }; var webRequest = new System.Net.Http.HttpClient(handler); respHTML = webRequest.GetStringAsync(url).GetAwaiter().GetResult(); //Console.WriteLine("xx"); } catch (Exception ex) { throw new Exception("获取HTML发生异常:" + ex.Message); //System.Windows.Forms.MessageBox.Show("获取信息发生异常:\r\n" + ex.Message + "\r\n" + Url); //Debug.WriteLine("Debug\\>GetHTML::Error(" + ex + ")"); } return(respHTML); }
private async Task <CLayer.Invoice> MessageFromHtml(long offid) { string url = ConfigurationManager.AppSettings.Get("InvoiceLink") + offid.ToString(); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); string mainHtml = await client.GetStringAsync(url); string html1, html2, html3, html4; int i, len; html1 = mainHtml; html1 = html1.Substring(html1.IndexOf("<!--#FIRSTROW_START-->")); len = html1.Length; i = html1.LastIndexOf("<!--#FIRSTROW_END-->"); html1 = html1.Substring(0, len - (len - i)); html2 = mainHtml; html2 = html2.Substring(html2.IndexOf("<!--#SECONDROW_START-->")); len = html2.Length; i = html2.LastIndexOf("<!--#SECONDROW_END-->"); html2 = html2.Substring(0, len - (len - i)); html3 = mainHtml; html3 = html3.Substring(html3.IndexOf("<!--#THIRDROW_START-->")); len = html3.Length; i = html3.LastIndexOf("<!--#THIRDROW_END-->"); html3 = html3.Substring(0, len - (len - i)); CLayer.Invoice data = BLayer.Invoice.GetInvoiceByOfflineBooking(offid); if (data == null) { return(null); } data.HtmlSection1 = html1; data.HtmlSection2 = html2; data.HtmlSection3 = html3; int OfflineBookingType = BLayer.OfflineBooking.GetBookingType(offid); if (OfflineBookingType == (int)CLayer.ObjectStatus.OfflineBookingType.Direct) { html4 = mainHtml; html4 = html4.Substring(html4.IndexOf("<!--#FOURTHROW_START-->")); len = html4.Length; i = html4.LastIndexOf("<!--#FOURTHROW_END-->"); html4 = html4.Substring(0, len - (len - i)); data.HtmlSection4 = html4; } else { data.HtmlSection4 = ""; } BLayer.Invoice.Save(data); return(data); }
public String GetString(String url) { var task = _client.GetStringAsync(url); Task.WaitAll(task); return(task.Result); }
public async Task GivenARequest_GetStringAsync_ReturnsAFakeResponse() { // Arrange. const string requestUri = "http://www.something.com/some/website"; const string responseContent = "hi"; var options = new HttpMessageOptions { HttpMethod = HttpMethod.Get, RequestUri = requestUri, HttpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(responseContent) } }; var messageHandler = new FakeHttpMessageHandler(options); string content; using (var httpClient = new System.Net.Http.HttpClient(messageHandler)) { // Act. content = await httpClient.GetStringAsync(requestUri); } // Assert. content.ShouldBe(responseContent); }
private async void Button_Click(object sender, RoutedEventArgs e) { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); string content = await client.GetStringAsync(new Uri(txtUrl.Text, UriKind.Absolute)); txtContent.Text = content; }
public UpdateChecker(Context ctx, DataBaseWrapper db, Setting setting) { if (string.IsNullOrEmpty (setting.NewestVersion)) { setting.NewestVersion = Setting.CurrentVersion; } var connectivityManager = (ConnectivityManager)ctx.GetSystemService(Context.ConnectivityService); if (setting.Synchronisation != Setting.Frequency.wlan || connectivityManager.GetNetworkInfo(ConnectivityType.Wifi).GetState() == NetworkInfo.State.Connected) { new Thread (async () => { string contentsTask; try { using(var httpClient = new HttpClient()) { contentsTask = await httpClient.GetStringAsync ("https://raw.githubusercontent.com/Bla-Chat/Android/master/version.txt"); } } catch (Exception e) { Log.Error ("BlaChat", e.StackTrace); contentsTask = null; } finally { //semaphore.Release (); } if (contentsTask != null) { setting.NewestVersion = contentsTask; db.Update(setting); } }).Start (); } }
public static async Task <string> MakeRequestAndLogFailures() { await logMethodEntrance(); var client = new System.Net.Http.HttpClient(); var streamTask = client.GetStringAsync("https://localhost:10000"); try { var responseText = await streamTask; return(responseText); } catch (System.Net.Http.HttpRequestException e) when(e.Message.Contains("301")) { await logError("Recovered from redirect", e); return("Site Moved"); } finally { await logMethodExit(); client.Dispose(); } }
private async void UpdateContributors() { try { var vms = await Task.Run(async () => { var hc = new HttpClient(); var str = await hc.GetStringAsync(App.ContributorsUrl); using (var sr = new StringReader(str)) { var xml = XDocument.Load(sr); return xml.Root .Descendants("contributor") .Where( e => e.Attribute("visible") == null || e.Attribute("visible").Value.ToLower() != "false") .Select(ContributorsViewModel.FromXml) .ToArray(); } }); await DispatcherHelper.UIDispatcher.InvokeAsync( () => { this.Contributors.Clear(); this.Contributors.Add(new ContributorsViewModel("thanks to:", null)); vms.OrderBy(v => v.ScreenName ?? "~" + v.Name) .ForEach(this.Contributors.Add); }); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
public async Task <JObject> GetJsonAsync() { Debug.WriteLine(uri); using (var client = new System.Net.Http.HttpClient()) { string jsonString = ""; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (type == RequestType.GET) { jsonString = await client.GetStringAsync(uri); Debug.WriteLine(jsonString); } else if (type == RequestType.POST) { CreateJsonContent(); System.Net.Http.HttpResponseMessage response = await client.PostAsync(uri, new StringContent(obj.ToString(), Encoding.UTF8, "application/json")); Debug.WriteLine("response : " + response.ToString()); jsonString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(jsonString); } else if (type == RequestType.DELETE) { System.Net.Http.HttpResponseMessage response = await client.DeleteAsync(uri); Debug.WriteLine("response : " + response.StatusCode.ToString()); jsonString = await response.Content.ReadAsStringAsync(); } Debug.WriteLine("jsonstring : " + jsonString); return(JObject.Parse(jsonString)); } }
public static string GetContents(Uri uri) { var client = new HttpClient(); var downloadTask = client.GetStringAsync(uri); downloadTask.WaitWithPumping(); return downloadTask.Result; }
public static async Task <string> DownloadFileAsync(string url) { using (System.Net.Http.HttpClient HC = new System.Net.Http.HttpClient()) { return(await HC.GetStringAsync(url)); } }
//9.await in catch finally block public async Task <string> AwaitInCatchFinallyBlock() { var client = new System.Net.Http.HttpClient(); try { await logger.Log("Enter the " + nameof(AwaitInCatchFinallyBlock)); var streamTask = client.GetStringAsync("https://localHost:10000"); var responseText = await streamTask; return(responseText); } catch (System.Net.Http.HttpRequestException e) when(e.Message.Contains("301")) { await logger.Log("Recovered from redirect", e); return("Site Moved"); } finally { await logger.Exit(); client.Dispose(); } }
/// <inheritdoc /> public async Task <SimplifiedHttpResponse> GetStringAsync(string url, string ifNoneMatch = null) { var request = new HttpRequestMessage(HttpMethod.Get, url); if (ifNoneMatch != null) { request.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch); } var response = await _httpClient.SendAsync(request); var newEtag = response.Headers.ETag.Tag; if (response.StatusCode == System.Net.HttpStatusCode.NotModified) { return(new SimplifiedHttpResponse() { NotModified = true, Body = null, Etag = newEtag }); } else { return(new SimplifiedHttpResponse() { NotModified = false, Body = await _httpClient.GetStringAsync(url), Etag = newEtag }); } }
public static async Task <string> GetButtonData() { using (var client = new System.Net.Http.HttpClient()) { return(await client.GetStringAsync(App.MainUrl)); } }
public async Task <JsonDefaultResponse <T> > Get <T>(string endpoint) { string response = await client.GetStringAsync(endpoint); var a = JsonTransformer.Deserialize <JsonDefaultResponse <T> >(response); return(a); }
//calculates the lag between the catalog and resolver in minutes private double CatalogToResolverLag(out JToken timeStampResolver) { System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); Task <string> cursorStringTask = client.GetStringAsync(new Uri(ResolverBlobsBaseUrl + "meta/cursor.json")); string cursorString = cursorStringTask.Result; // Not async! JObject cursorJson = JObject.Parse(cursorString); DateTime cursorTimestamp = cursorJson["http://schema.nuget.org/collectors/resolver#cursor"]["@value"].ToObject <DateTime>(); Task <string> catalogIndexStringTask = client.GetStringAsync(CatalogUrl); string catalogIndexString = catalogIndexStringTask.Result; JObject catalogIndex = JObject.Parse(catalogIndexString); DateTime catalogTimestamp = catalogIndex["commitTimestamp"].ToObject <DateTime>(); TimeSpan span = catalogTimestamp - cursorTimestamp; double delta = span.TotalMinutes; timeStampResolver = cursorTimestamp; return(delta); }
public static async Task <string> DownloadContent() { using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient()) { string result = await client.GetStringAsync("http://www.microsoft.com"); return(result); } }
private async Task <string> GetMailBody(long obid) { string url = ConfigurationManager.AppSettings.Get("InvoiceMailLink") + obid.ToString(); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); string mainHtml = await client.GetStringAsync(url); return(mainHtml); }
public string LoadPage(string pageUrl) { HttpClient http = new System.Net.Http.HttpClient(); Task <string> taskString = http.GetStringAsync(pageUrl); taskString.Wait(); return(taskString.Result); }
public async Task Mastery(string region, [Remainder] string name) { var db = new BotBaseContext(); var embed = new JifBotEmbedBuilder(); { name = name.Replace(" ", string.Empty); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); string html = ""; try { html = await client.GetStringAsync("https://championmasterylookup.derpthemeus.com/summoner?summoner=" + name + "®ion=" + region.ToUpper()); } catch { await ReplyAsync("That summoner does not exist"); return; } html = html.Remove(0, html.IndexOf("/img/profile")); embed.ThumbnailUrl = "https://championmasterylookup.derpthemeus.com" + html.Remove(html.IndexOf("\"")); html = html.Remove(0, html.IndexOf("userName="******"Top ten mastery scores for " + (html.Remove(html.IndexOf("\"")).Replace("%20", " ")); string champ = ""; string nums = ""; int count = 0; for (int i = 1; i <= 10; i++) { if (html.IndexOf("/champion?") == html.IndexOf("/champion?champion=-1")) { break; } html = html.Remove(0, html.IndexOf("/champion?")); html = html.Remove(0, html.IndexOf(">") + 1); champ = html.Remove(html.IndexOf("<")); champ = champ.Replace("'", "'"); html = html.Remove(0, html.IndexOf("\"") + 1); nums = html.Remove(html.IndexOf("\"")); count = count + Convert.ToInt32(nums); for (int j = nums.Length - 3; j > 0; j = j - 3) { nums = nums.Remove(j) + "," + nums.Remove(0, j); } embed.AddField(i + ". " + champ, nums + " points", inline: true); } nums = Convert.ToString(count); for (int j = nums.Length - 3; j > 0; j = j - 3) { nums = nums.Remove(j) + "," + nums.Remove(0, j); } embed.Description = "Total score across top ten: " + nums; await ReplyAsync("", false, embed.Build()); } }
public async Task SimpleGetString() { var client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri("https://en.wikipedia.org/w/api.php"); var result = await client.GetStringAsync("?action=query&prop=info&titles=Main%20Page&format=json"); _testOutputHelper.WriteLine($"Text: {result}"); }
public async Task Youtube([Remainder] string vid) { vid = "https://www.youtube.com/results?search_query=" + vid.Replace(" ", "+"); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); string html = await client.GetStringAsync(vid); html = html.Remove(0, html.IndexOf("?v=") + 3); html = html.Remove(html.IndexOf("\"")); await ReplyAsync("https://www.youtube.com/watch?v=" + html); }
public async Task ReturnsNewResponseInstanceEachRequest() { handler.SetupRequest(HttpMethod.Get, "https://example.com/foo") // Handler doesn't know about client's BaseAddress .ReturnsResponse("bar"); var response1 = await client.GetAsync("foo"); var response2 = await client.GetAsync("foo"); // New instances are returned for each request to ensure that subsequent requests don't receive a disposed // HttpResponseMessage or HttpContent response2.Should().NotBeSameAs(response1, "each request should get its own response object"); response2.Content.Should().NotBeSameAs(response1.Content, "each response should have its own content object"); // HttpClient.GetStringAsync() wraps the HttpResponseMessage in a `using` (up until at least .NET 5) (await client.GetStringAsync("foo")).Should().Be("bar"); (await client.GetStringAsync("foo")).Should().Be("bar", "the HttpContent should not be disposed"); handler.VerifyRequest(HttpMethod.Get, "https://example.com/foo", Times.Exactly(4)); }
private async Task <string> GetRemoteResult1Async() { using (var client = new System.Net.Http.HttpClient()) { sb.Append($"呼叫讀取 Web API 非同方法 前 的執行緒 : {Thread.CurrentThread.ManagedThreadId}{Environment.NewLine}{Environment.NewLine}"); var result = await client.GetStringAsync(URL); sb.Append($"呼叫讀取 Web API 非同方法 後 的執行緒 : {Thread.CurrentThread.ManagedThreadId}{Environment.NewLine}{Environment.NewLine}"); return(result); } }
private static void RunQueries() { HttpClient client = new HttpClient(); // Showing the aliased names in the $metadata document. // The metadata will display Customer instead of CustomerDto, etc. Console.WriteLine("Showing the metadata document with the aliased names"); Console.WriteLine(); Console.WriteLine(client.GetStringAsync(serverUrl + "/odata/$metadata").Result); Console.WriteLine(); // Querying for a customer to see the aliased payload. // Check that the payload reflects that GivenName is aliased to FirstName. Console.WriteLine("Querying a single customer at /Customers(1):"); Console.WriteLine(); Console.WriteLine(client.GetStringAsync(serverUrl + "/odata/Customers").Result); Console.WriteLine(); // Querying the customers feed and using the aliased property name on a $filter clause. // Look at the FirstName property in the query string instead of GivenName as in the CLR object. Console.WriteLine("Querying for the feed of customers and filtering on an aliased property:"); Console.WriteLine(); Console.WriteLine(client.GetStringAsync(serverUrl + "/odata/Customers?$filter=FirstName le 'First name 5'").Result); Console.WriteLine(); // Querying the orders of a customer. // Look at the Orders property in the path of the URI instead of Purchases on the CLR type name. Console.WriteLine("Querying for the orders associated to a customer:"); Console.WriteLine(); Console.WriteLine(client.GetStringAsync(serverUrl + "/odata/Customers(1)/Orders").Result); }