public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed) { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Bind(new IPEndPoint(IPAddress.Loopback, 0)); s.Listen(1); var ep = (IPEndPoint)s.LocalEndPoint; using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getAsync = client.GetAsync($"http://{ep.Address}:{ep.Port}", HttpCompletionOption.ResponseHeadersRead); using (Socket server = s.Accept()) using (Stream serverStream = new NetworkStream(server, ownsSocket: false)) using (StreamReader reader = new StreamReader(serverStream, Encoding.ASCII)) { string line; while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ; byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders); serverStream.Write(headerData, 0, headerData.Length); } if (shouldSucceed) { (await getAsync).Dispose(); } else { await Assert.ThrowsAsync<HttpRequestException>(() => getAsync); } } } }
public static async Task<string> HttpGets(string uri) { if (Config.IsNetWork) { NotifyControl notify = new NotifyControl(); notify.Text = "亲,努力加载中..."; notify.Show(); using (HttpClient httpClient = new HttpClient()) { try { HttpResponseMessage response = new HttpResponseMessage(); response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute)); responseString = await response.Content.ReadAsStringAsync(); notify.Hide(); } catch (Exception ex) { Debug.WriteLine(ex.Message.ToString()); } } } return responseString; }
public async Task<LogOnResult> LogOnAsync(string userId, string password) { using (var client = new HttpClient()) { // Ask the server for a password challenge string var requestId = CryptographicBuffer.EncodeToHexString(CryptographicBuffer.GenerateRandom(4)); var challengeResponse = await client.GetAsync(new Uri(_clientBaseUrl + "GetPasswordChallenge?requestId=" + requestId)); challengeResponse.EnsureSuccessStatusCode(); var challengeEncoded = await challengeResponse.Content.ReadAsStringAsync(); challengeEncoded = challengeEncoded.Replace(@"""", string.Empty); var challengeBuffer = CryptographicBuffer.DecodeFromHexString(challengeEncoded); // Use HMAC_SHA512 hash to encode the challenge string using the password being authenticated as the key. var provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha512); var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); var hmacKey = provider.CreateKey(passwordBuffer); var buffHmac = CryptographicEngine.Sign(hmacKey, challengeBuffer); var hmacString = CryptographicBuffer.EncodeToHexString(buffHmac); // Send the encoded challenge to the server for authentication (to avoid sending the password itself) var response = await client.GetAsync(new Uri(_clientBaseUrl + userId + "?requestID=" + requestId + "&passwordHash=" + hmacString)); // Raise exception if sign in failed response.EnsureSuccessStatusCode(); // On success, return sign in results from the server response packet var responseContent = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<UserInfo>(responseContent); var serverUri = new Uri(Constants.ServerAddress); return new LogOnResult { UserInfo = result }; } }
public async Task<bool> SendRequest() { try { var config = new ConfigurationViewModel(); var uri = new Uri(config.Uri + _path); var filter = new HttpBaseProtocolFilter(); if (config.IsSelfSigned == true) { filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); } var httpClient = new HttpClient(filter); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("text/plain")); httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Mozilla", "5.0").ToString())); httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Firefox", "26.0").ToString())); var reponse = await httpClient.GetAsync(uri); httpClient.Dispose(); return reponse.IsSuccessStatusCode; } catch (Exception) { return false; } }
static public async Task<string> SendGetRequest ( string address ) { var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter (); httpFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent; httpClient = new HttpClient ( httpFilter ); response = new HttpResponseMessage (); string responseText = ""; //check address Uri resourceUri; if ( !Uri.TryCreate ( address.Trim () , UriKind.Absolute , out resourceUri ) ) { return "Invalid URI, please re-enter a valid URI"; } if ( resourceUri.Scheme != "http" && resourceUri.Scheme != "https" ) { return "Only 'http' and 'https' schemes supported. Please re-enter URI"; } //get try { response = await httpClient.GetAsync ( resourceUri ); response.EnsureSuccessStatusCode (); responseText = await response.Content.ReadAsStringAsync (); } catch ( Exception ex ) { // Need to convert int HResult to hex string responseText = "Error = " + ex.HResult.ToString ( "X" ) + " Message: " + ex.Message; } httpClient.Dispose (); return responseText; }
public static async Task<string> GetTextByGet(string posturi) { var httpClient = new HttpClient(); var response = await httpClient.GetAsync(new Uri(posturi)); string responseString = await response.Content.ReadAsStringAsync(); return responseString; }
public async void Execute(string token, string content) { Uri uri = new Uri(API_ADDRESS + path); var rootFilter = new HttpBaseProtocolFilter(); rootFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent; rootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache; HttpClient client = new HttpClient(rootFilter); //client.DefaultRequestHeaders.Add("timestamp", DateTime.Now.ToString()); if(token != null) client.DefaultRequestHeaders.Add("x-access-token", token); System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000); HttpResponseMessage response = null; if (requestType == GET) { try { response = await client.GetAsync(uri).AsTask(source.Token); } catch (TaskCanceledException) { response = null; } }else if (requestType == POST) { HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), uri); if (content != null) { msg.Content = new HttpStringContent(content); msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); } try { response = await client.SendRequestAsync(msg).AsTask(source.Token); } catch (TaskCanceledException) { response = null; } } if (response == null) { if (listener != null) listener.onTaskCompleted(null, requestCode); } else { string answer = await response.Content.ReadAsStringAsync(); if(listener != null) listener.onTaskCompleted(answer, requestCode); } }
public async Task<Model.Recipef2f> getRecipe(String recipeId) { var httpClient = new HttpClient(); var uri = new Uri(stringUri+recipeId); HttpResponseMessage result = await httpClient.GetAsync(uri); Model.Recipef2f recipe = new Model.Recipef2f(); JsonObject jsonObject = JsonObject.Parse(result.Content.ToString()); JsonObject jsonValue = jsonObject.GetNamedObject("recipe", new JsonObject()); recipe.Publisher = jsonValue.GetNamedString("publisher", ""); recipe.F2fUrl = jsonValue.GetNamedString("f2f_url", ""); JsonArray ingredientsArray = jsonValue.GetNamedArray("ingredients"); foreach(JsonValue ingredient in ingredientsArray) { recipe.IngredientsList += ingredient.ToString() + " \n "; } recipe.SourceUrl = jsonValue.GetNamedString("source_url", ""); recipe.ImageUrl = jsonValue.GetNamedString("image_url", ""); recipe.SocialRank = jsonValue.GetNamedNumber("social_rank", 0); recipe.PublisherUrl = jsonValue.GetNamedString("publisher_url", ""); recipe.Title = jsonValue.GetNamedString("title", ""); recipe.RecipeId = recipeId; return recipe; }
public async Task<bool> IsInFastFood(GeoCoordinate geo) { XmlDocument doc = new XmlDocument(); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Add("Accept", "text/xml"); var squarreSize = 0.0002; var url = "http://api.openstreetmap.org/api/0.6/map?bbox=" + (geo.Longitude - squarreSize).ToString("G", CultureInfo.InvariantCulture) + "," + (geo.Latitude - squarreSize).ToString("G", CultureInfo.InvariantCulture) + "," + (geo.Longitude + squarreSize).ToString("G", CultureInfo.InvariantCulture) + "," + (geo.Latitude + squarreSize).ToString("G", CultureInfo.InvariantCulture) + "&page=0"; var uri = new Uri(url); HttpResponseMessage response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var s = await response.Content.ReadAsStringAsync(); doc.LoadXml(s); var listNodeTag = doc.SelectNodes("//tag[@k='amenity'][@v='fast_food']"); // var listNodeTag = doc.SelectNodes("//tag[@k='bus'][@v='bus']"); //var busFound = s.IndexOf("bus") > 0; if (listNodeTag.Count > 0) { return true; } } } return false; }
public static async Task<string> HttpGet(string uri) { if (Config.IsNetWork) { NotifyControl notify = new NotifyControl(); notify.Text = "亲,努力加载中..."; notify.Show(); var _filter = new HttpBaseProtocolFilter(); using (HttpClient httpClient = new HttpClient(_filter)) { _filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; HttpResponseMessage response = new HttpResponseMessage(); response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute)); responseString = await response.Content.ReadAsStringAsync(); notify.Hide(); } } return responseString; }
private static async Task<ObservableCollection<Activity>> GetActvityDataAsync(int locationId = 0, int profileId = 0) { var activities = new ObservableCollection<Activity>(); using (var httpClient = new HttpClient()) { var apiKey = Common.StorageService.LoadSetting("ApiKey"); var apiUrl = Common.StorageService.LoadSetting("ApiUrl"); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip"); httpClient.DefaultRequestHeaders.Add("token", apiKey); httpClient.DefaultRequestHeaders.Add("api-version", "2"); try { var url = apiUrl + "/api/activity"; if (locationId > 0) { url = url + "/location/" + locationId.ToString(); } if (profileId > 0) { url = url + "/profile/" + profileId.ToString(); } var httpResponse = await httpClient.GetAsync(new Uri(url)); string json = await httpResponse.Content.ReadAsStringAsync(); json = json.Replace("<br>", Environment.NewLine); activities = JsonConvert.DeserializeObject<ObservableCollection<Activity>>(json); } catch (Exception e) { } } return activities; }
async public static Task<AllStationList> GetStationData() { var httpClient = new HttpClient(); var response = await httpClient.GetAsync( new Uri("https://api.jcdecaux.com/vls/v1/stations?contract=paris&apiKey=2ea0e103b64bb80ce93b2cc73089d8de7dd7481d") ); if (response.IsSuccessStatusCode) { var stationsJson = JsonArray.Parse(await response.Content.ReadAsStringAsync()); return new AllStationList(stationsJson.Select(station => { var number = (int)station.GetObject()["number"].GetNumber(); var name = station.GetObject()["name"].GetString(); var address = station.GetObject()["address"].GetString(); var latitude = station.GetObject()["position"].GetObject()["lat"].GetNumber(); var longitude = station.GetObject()["position"].GetObject()["lng"].GetNumber(); var banking = station.GetObject()["banking"].GetBoolean(); var bonus = station.GetObject()["bonus"].GetBoolean(); var status = station.GetObject()["status"].GetString(); var totalStands = (int)station.GetObject()["bike_stands"].GetNumber(); var availableStands = (int)station.GetObject()["available_bike_stands"].GetNumber(); var availableBikes = (int)station.GetObject()["available_bikes"].GetNumber(); var lastUpdate = (long)station.GetObject()["last_update"].GetNumber(); return new Station(number, name, address, latitude, longitude, banking, bonus, status, totalStands, availableBikes, availableStands, lastUpdate); })); } else return null; }
public async Task<bool> tokenIsValid() { string access_token = null; if (tokenExists()) { access_token = (string)ApplicationData.Current.LocalSettings.Values["Tokens"]; string href = "https://api.teamsnap.com/v3/me"; HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", access_token); httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json")); try { var httpResponseMessage = await httpClient.GetAsync(new Uri(href)); Debug.WriteLine("http response status code : " + httpResponseMessage.StatusCode.ToString()); if (httpResponseMessage.StatusCode.ToString().Equals("Ok")) { return true; } } catch (Exception ex) { Debug.WriteLine("Caught an Exception in tokenIsValid() " + ex); return false; } } Debug.WriteLine("tokenIsValid : Invalid token . returning false"); return false; }
public async Task Automatic_SSLBackendNotSupported_ThrowsPlatformNotSupportedException() { using (var client = new HttpClient(new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Automatic })) { await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)); } }
private static async Task<string> GetRequest(string uri) { try { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(new Uri(uri)); if (!response.IsSuccessStatusCode) { if (response.StatusCode == HttpStatusCode.InternalServerError) { throw new Exception(HttpStatusCode.InternalServerError.ToString()); } else { // Throw default exception for other errors response.EnsureSuccessStatusCode(); } } return await response.Content.ReadAsStringAsync(); } } catch (Exception) { if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger System.Diagnostics.Debugger.Break(); } throw; } }
static async Task<string> Get(string gameType) { string url = "http://puzzle.win2012r2.oasis.dnnsharp.com/DesktopModules/DnnSharp/DnnApiEndpoint/Api.ashx?method=Highscore&GameType=" + gameType + "&datetime=" + DateTime.Now.ToString(); try { //Create Client var client = new HttpClient(); var uri = new Uri(url); //Call.Get response by Async var Response = await client.GetAsync(uri); //Result & Code Windows.Web.Http.HttpStatusCode statusCode = Response.StatusCode; //If Response is not Http 200 //then EnsureSuccessStatusCode will throw an exception Response.EnsureSuccessStatusCode(); return await Response.Content.ReadAsStringAsync(); } catch (Exception ex) { //... return ""; } }
public async Task<HttpResult> GetAsync(string url) { HttpResult ret = new HttpResult(); try { using (HttpClient client = new HttpClient()) { TryAddHeaders(client); using (HttpResponseMessage response = await client.GetAsync(new Uri(url))) { if (response != null && response.IsSuccessStatusCode) { var responseText = await response.Content.ReadAsStringAsync(); ret.Result = responseText; ret.Success = true; } } } } catch (Exception ex) { Logging.Logger.Log(Logging.LogType.Exception, "GetAsync:" + url, ex); } return ret; }
public static async Task<List<Light>> RetrieveLights() { var cts = new CancellationTokenSource(); List<Light> retVal = new List<Light>(); cts.CancelAfter(5000); try { HttpClient client = new HttpClient(); string ip, username; int port; SettingsService.RetrieveSettings(out ip, out port, out username); var response = await client.GetAsync(new Uri(string.Format("http://{0}:{1}/api/{2}/lights/", ip, port, username))).AsTask(cts.Token); if (!response.IsSuccessStatusCode) { cts.Cancel(); } string jsonResponse = await response.Content.ReadAsStringAsync(); //System.Diagnostics.Debug.WriteLine(jsonResponse); retVal = ParseLights(jsonResponse); var IgnoredTask = UpdateLightsPhraseList(retVal); IgnoredTask.Start(); } catch (Exception) { cts.Cancel(); } return retVal; }
internal static async Task<InternetRequestResult> DownloadAsync(InternetRequestSettings settings) { InternetRequestResult result = new InternetRequestResult(); try { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); if (!string.IsNullOrEmpty(settings.UserAgent)) { httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(settings.UserAgent); } HttpResponseMessage response = await httpClient.GetAsync(settings.RequestedUri); result.StatusCode = response.StatusCode; if (response.IsSuccessStatusCode) { FixInvalidCharset(response); result.Result = await response.Content.ReadAsStringAsync(); } } catch (Exception) { result.StatusCode = HttpStatusCode.InternalServerError; result.Result = string.Empty; } return result; }
/// <summary> /// Banner,推荐,最新 /// </summary> private async void GetDYHome() { try { pro_Bar.Visibility = Visibility.Visible; using (hc = new HttpClient()) { HttpResponseMessage hr = await hc.GetAsync(new Uri("http://app.bilibili.com/api/region2/23.json")); hr.EnsureSuccessStatusCode(); var encodeResults = await hr.Content.ReadAsBufferAsync(); string results = Encoding.UTF8.GetString(encodeResults.ToArray(), 0, encodeResults.ToArray().Length); DHModel model = JsonConvert.DeserializeObject<DHModel>(results); DHModel model2 = JsonConvert.DeserializeObject<DHModel>(model.result.ToString()); List<DHModel> BannerModel = JsonConvert.DeserializeObject<List<DHModel>>(model2.banners.ToString()); //List<DHModel> RecommendsModel = JsonConvert.DeserializeObject<List<DHModel>>(model2.recommends.ToString()); //List<DHModel> NewsModel = JsonConvert.DeserializeObject<List<DHModel>>(model2.news.ToString()); home_flipView.Items.Clear(); foreach (DHModel item in BannerModel) { if (item.aid != null || item.img != null) { home_flipView.Items.Add(item); } } } pro_Bar.Visibility = Visibility.Collapsed; } catch (Exception ex) { MessageDialog md = new MessageDialog(ex.Message); await md.ShowAsync(); } }
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation) { var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { bool callbackCalled = false; handler.CheckCertificateRevocationList = checkRevocation; handler.ServerCertificateValidationCallback = (request, cert, chain, errors) => { callbackCalled = true; Assert.NotNull(request); Assert.Equal(SslPolicyErrors.None, errors); Assert.True(chain.ChainElements.Count > 0); Assert.NotEmpty(cert.Subject); Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode); return true; }; using (HttpResponseMessage response = await client.GetAsync(url)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } Assert.True(callbackCalled); } }
public void ProxyExplicitlyProvided_DefaultCredentials_Ignored() { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true); Uri proxyUrl = new Uri($"http://localhost:{port}"); var rightCreds = new NetworkCredential("rightusername", "rightpassword"); var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword"); using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds); handler.DefaultProxyCredentials = wrongCreds; Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer); Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap(); Task.WaitAll(proxyTask, responseTask, responseStringTask); TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null); Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result); string expectedAuth = $"{rightCreds.UserName}:{rightCreds.Password}"; Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue); } }
public static async Task<List<FlickrImage>> SearchAsync(string tag) { var client = new HttpClient(); const string apiKey = "8ebe03ac6480c2c43aeaf1183eec0eb9"; const string baseUri = "https://api.flickr.com/services/rest/?method=flickr.photos.search&safe_search=1&per_page=25&content_type=1&media=photos&"; var url = string.Format( baseUri + "api_key={0}&" + "page={1}&" + "tags={2}", apiKey, 1, tag); var list = new List<FlickrImage>(); using (var response = await client.GetAsync(new Uri(url, UriKind.Absolute))) { if (response.IsSuccessStatusCode) { var contentxml = await response.Content.ReadAsStringAsync(); var xml = XElement.Parse(contentxml); list = (from p in xml.DescendantsAndSelf("photo") select new FlickrImage(p)).ToList(); } } return list; }
public async Task ThresholdExceeded_ThrowsException(string responseHeaders, int maxResponseHeadersLength, bool shouldSucceed) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getAsync = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); await LoopbackServer.AcceptSocketAsync(server, async (s, serverStream, reader, writer) => { using (s) using (serverStream) using (reader) using (writer) { string line; while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) ; byte[] headerData = Encoding.ASCII.GetBytes(responseHeaders); serverStream.Write(headerData, 0, headerData.Length); } if (shouldSucceed) { (await getAsync).Dispose(); } else { await Assert.ThrowsAsync<HttpRequestException>(() => getAsync); } return null; }); } }); }
private async Task<String> Get(string path) { var cts = new CancellationTokenSource(); cts.CancelAfter(5000); try { HttpClient client = new HttpClient(); Uri uriLampState = new Uri("http://127.0.0.1:8000/api/" + path); var response = await client.GetAsync(uriLampState).AsTask(cts.Token); if (!response.IsSuccessStatusCode) { return string.Empty; } string jsonResponse = await response.Content.ReadAsStringAsync(); return jsonResponse; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return string.Empty; } }
public async Task RefreshTokenAsync() { var http = new HttpClient(); var resp = await http.GetAsync(new Uri("http://bandontherun.azurewebsites.net/api/getsastoken/dxband")); resp.EnsureSuccessStatusCode(); _sas = await resp.Content.ReadAsStringAsync(); _sas = _sas.Trim('"'); }
private static void refreshFeeds(User user) { foreach (PodcastRssFeedXmlSurrogate.rss rssFeed in user.Subscriptions) { HttpClient client = new HttpClient(); var response = client.GetAsync(new Uri(rssFeed.channel.link)); } }
static async Task Notify(string msg, bool isFailed = false) { Console.WriteLine(msg); if (_conf.ScType == "Always" || (isFailed && _conf.ScType == "Failed")) { await _scClient?.GetAsync($"https://sc.ftqq.com/{_conf.ScKey}.send?text={msg}"); } }
private async void init() { HttpClient hc = new HttpClient(); HttpResponseMessage hr = await hc.GetAsync(new Uri("http://m.kugou.com/loginReg.php?act=login&url=http://kugou.com")); webview.Source = new Uri("http://m.kugou.com/loginReg.php?act=login&url=http://m.kugou.com"); webview.NavigationCompleted += Webview_NavigationCompleted; webview.ScriptNotify += Webview_ScriptNotify; }
public async Task <string> GetNodesList(MonitorNet net) { HttpClient _restClient = new HttpClient { }; HttpResponseMessage resultMessage; if (net == MonitorNet.MainNet) { resultMessage = await _restClient?.GetAsync(monitorCityOfZionMainNet); } else { resultMessage = await _restClient?.GetAsync(monitorCityOfZionTestNet); } var data = await resultMessage.Content.ReadAsStringAsync(); return(data); }
private async void ResolutionSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs <double> e) { int value = (int)e.NewValue; value = SelectResolution(value); string address = baseAddress + controlSuffix + var + framesize + val + value; client?.GetAsync(address); await Task.Delay(500); w = (int)leftCameraImage.ActualWidth; h = (int)leftCameraImage.ActualHeight; resolutionLabel.Content = $"{w}x{h}px"; }
/// <summary> /// Generic method that can be used for all GET requests /// </summary> /// <param name="URI">Web api method url</param> /// <returns></returns> private string CallGetRestEndpoint(string URI) { try { HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = true }; using (var client = new HttpClient(handler)) { client.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebAPIurl"].ToString()); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync(URI).Result; var res = response.Content.ReadAsStringAsync().Result; return(res); } } catch (Exception ex) { return(string.Format("Exception in CallGetRestEndpoint URI: {0}, Error: {1} ", URI, ex.Message)); } }
/// <summary> /// Calls the REST Countries API to get countries matching the given country name /// </summary> /// <param name="countryName">All or the first part of a country name to match</param> /// <returns>Collection of matching countries</returns> public async Task <ICollection <Country> > GetCountriesAsync(string countryName) { if (string.IsNullOrEmpty(countryName)) { throw new ArgumentNullException(nameof(countryName)); } //TODO: Ideally I'd use something like WebUtility.UrlEncode here - but that doesn't return the expected encoding var encodedCountryName = countryName.Replace(" ", "%20"); var apiUrl = string.Format(_appSettings.CurrentValue.CountryApiUrl, encodedCountryName); var response = await _client.GetAsync(apiUrl); var responseContent = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject <ICollection <Country> >(responseContent)); } throw new ApplicationException($"Failed to call Weather API. Status code: {response.StatusCode}"); }
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol) { using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { if (requestOnlyThisProtocol) { handler.SslProtocols = acceptedProtocol; } var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options), client.GetAsync(url)); }, options); } }
public async void GetMany_OrgRequestsAllInstances_Ok() { // Arrange string requestUri = $"{BasePath}?org=ttd"; HttpClient client = GetTestClient(); string token = PrincipalUtil.GetOrgToken("ttd", scope: "altinn:instances.read"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); int expectedNoInstances = 10; // Act HttpResponseMessage response = await client.GetAsync(requestUri); string json = await response.Content.ReadAsStringAsync(); InstanceQueryResponse queryResponse = JsonConvert.DeserializeObject <InstanceQueryResponse>(json); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedNoInstances, queryResponse.TotalHits); }
public override async Task <HeartBeatData> GetDataAsync(CancellationToken cancellationToken = default) { var httpClient = new HttpClient(); var stopwatcher = new Stopwatch(); stopwatcher.Start(); try { var response = await httpClient.GetAsync($"{ConfigProvider.GetConfigEntry($"{RootConfig}:HeartBeatAddress")}", cancellationToken); stopwatcher.Stop(); if (response.IsSuccessStatusCode) { return(new HeartBeatData((int)stopwatcher.ElapsedMilliseconds, Status.OK)); } return(new HeartBeatData(0, Status.OK)); } catch (Exception ex) { return(HeartBeatData.Error(ex.Message + ex.InnerException.Message)); } }
public async Task GetAsync_ResponseHasNormalLineEndings_Success(string lineEnding) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { Task <HttpResponseMessage> getResponseTask = client.GetAsync(url); Task <List <string> > serverTask = server.AcceptConnectionSendCustomResponseAndCloseAsync( $"HTTP/1.1 200 OK{lineEnding}Date: {DateTimeOffset.UtcNow:R}{lineEnding}Server: TestServer{lineEnding}Content-Length: 0{lineEnding}{lineEnding}"); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(200, (int)response.StatusCode); Assert.Equal("OK", response.ReasonPhrase); Assert.Equal("TestServer", response.Headers.Server.ToString()); } } }, new LoopbackServer.Options { StreamWrapper = GetStream }); }
public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination, CancellationToken cancellationToken = default, IProgress <double> progress = null) { using (var resp = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead)) { var contentLength = resp.Content.Headers.ContentLength; using (var download = await resp.Content.ReadAsStreamAsync()) { if (progress == null || !contentLength.HasValue) { await download.CopyToAsync(destination); return; } var relativeProgress = new Progress <int>(totalBytes => progress.Report((double)totalBytes / contentLength.Value)); await download.CopyToAsync(destination, 8192, cancellationToken, relativeProgress); progress.Report(1); } } }
public async Task <JObject> GetCompanyData(string krsNumber) { using (HttpClient client = new HttpClient()) { try { HttpResponseMessage response = await client.GetAsync(GET_COMPANY_DATA_URL + krsNumber); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); JObject json = JObject.Parse(responseBody); return(json); } catch (HttpRequestException e) { Debug.WriteLine($"{nameof(this.GetCompanyData)} exception caught:"); Debug.WriteLine(e.Message); throw; } } }
public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination, IProgress <double>?progress = default, CancellationToken cancellationToken = default) { using var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var contentLength = response.Content.Headers.ContentLength; response.EnsureSuccessStatusCode(); using var download = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); if (progress == null || !contentLength.HasValue) { await download.CopyToAsync(destination).ConfigureAwait(false); return; } var relativeProgress = new Progress <long>(totalBytes => progress.Report((float)totalBytes / contentLength.Value)); await download.CopyToAsync(destination, 81920, relativeProgress, cancellationToken).ConfigureAwait(false); progress.Report(1); }
private static async Task <dynamic> Get(string endpoint, bool noCache = false) { PluginLog.Verbose("XIVAPI FETCH: {0}", endpoint); if (CachedResponses.TryGetValue(endpoint, out var val) && !noCache) { return(val); } var client = new HttpClient(); var response = await client.GetAsync(URL + endpoint); var result = await response.Content.ReadAsStringAsync(); var obj = JObject.Parse(result); if (!noCache) { CachedResponses.TryAdd(endpoint, obj); } return(obj); }
// GET: Booking/List public async Task<IActionResult> List() { List<Booking> bookingList = new List<Booking>(); HttpClient client = _bookingApi.InitializeClient(); HttpResponseMessage res = await client.GetAsync("api/booking"); //Checking the response is successful or not which is sent using HttpClient if (res.IsSuccessStatusCode) { //Storing the response details recieved from web api var result = res.Content.ReadAsStringAsync().Result; //Deserializing the response recieved from web api and storing into the list bookingList = JsonConvert.DeserializeObject<List<Booking>>(result); } //returning the list to view return View(bookingList); }
public string ApiCall(string urlParameters) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseURL); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/xml")); // List data response. HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! return(response.Content.ReadAsStringAsync().Result); } else { return((int)response.StatusCode + response.ReasonPhrase); } }
public static async Task <bool> WakeAndroidDevices(string userId) { try { var httpClient = new HttpClient(); var response = await httpClient.GetAsync($"{Constants.ServerAddress}/api/User/{userId}/TryWakeAll"); var responseText = await response.Content.ReadAsStringAsync(); if (responseText != "1, done") { Debug.WriteLine($"Received unexpected message from TryWakeAll: '{responseText}'"); return(false); } } catch (Exception ex) { Debug.WriteLine($"An exception was thrown in WakeAndroidDevices: {ex.Message}"); return(false); } return(true); }
public async Task <Operator> GetOperatorAsync(Guid operatorId) { var uri = constant.Host + constant.Port + "operators/" + operatorId; Operator ope = new Operator(); try { var response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); ope = JsonConvert.DeserializeObject <Operator>(content); } return(ope); } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } }
public ActionResult Edit(int id) { ViajerosViewModel viajero = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:8092/api/"); //HTTP GET var responseTask = client.GetAsync("tm_via_viajeros?id=" + id.ToString()); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync <ViajerosViewModel>(); readTask.Wait(); viajero = readTask.Result; } } return(View(viajero)); }
public IActionResult Account() { var url = "http://localhost:5000/api/users/me"; var jwt = GetJWT(); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt); HttpResponseMessage resp = client.GetAsync(url).Result; Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(resp)); if (resp.IsSuccessStatusCode) { return(View( JsonConvert.DeserializeObject <Users>(resp.Content.ReadAsStringAsync().Result) )); } else { return(Redirect("/Home/Signin")); } }
// GET: Genre/Details/5 public async Task <ActionResult> Details(int id) { IEnumerable <GenreModel> genres = null; GenreModel genre = null; string serviceUrl = "https://animegination2.azurewebsites.net/api/categories/" + id.ToString(); using (var client = new HttpClient()) { client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); client.DefaultRequestHeaders.TryAddWithoutValidation("AnimeApiClientKey", "AA46C009-49F8-4411-A4D6-131D4BA6D91B"); client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json"); using (var response = await client.GetAsync(serviceUrl)) { string apiResponse = await response.Content.ReadAsStringAsync(); genres = JsonConvert.DeserializeObject <IEnumerable <GenreModel> >(apiResponse); genre = genres.FirstOrDefault(); } } return(View(genre)); }
public async Task <List <RentBreakdown> > GetRentBreakdown(string tagRef) { var queryDictionary = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(tagRef)) { queryDictionary.Add("tenancyAgreementId", tagRef); } var rqpString = new FormUrlEncodedContent(queryDictionary).ReadAsStringAsync().Result; var builder = new UriBuilder { Query = rqpString }; var response = await _client.GetAsync(new Uri("GetAllRentBreakdowns" + builder.Query, UriKind.Relative)).ConfigureAwait(true); var content = await response.Content.ReadAsStringAsync().ConfigureAwait(true); var results = JsonConvert.DeserializeObject <List <RentBreakdown> >(content); return(results); }
public Formnv() { InitializeComponent(); cmbgt.Text = "Nam"; HttpClient client = new HttpClient(); client.BaseAddress = new Uri("https://localhost:44326/"); HttpResponseMessage response = client.GetAsync("api/Employees").Result; var employee = response.Content.ReadAsAsync <IEnumerable <Employee> >().Result; gvnv.DataSource = employee; gvnv.Columns["MaNV"].HeaderText = "Mã nhân viên"; gvnv.Columns["Hoten"].HeaderText = "Họ tên"; gvnv.Columns["Gioitinh"].HeaderText = "Giới tính"; gvnv.Columns["SDT"].HeaderText = "Số điện thoại"; gvnv.Columns["Hinh"].HeaderText = "Hình ảnh"; gvnv.Columns["Ghichu"].HeaderText = "Ghi chú"; eml = employee.ToList(); txtmanv.Enabled = txthoten.Enabled = txtghichu.Enabled = btnquaylai.Enabled = btnxacnhan.Enabled = txtdt.Enabled = btnbrowse.Enabled = cmbgt.Enabled = false; }
/// <summary> /// Send a GET request. Access token is taken care of. /// </summary> /// <param name="url"></param> /// <returns></returns> public async Task <T> SendHttpGetAsync <T>(string url) { AccessToken = await GetAccessToken(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(BaseUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Add the authorization header with the access token. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + AccessToken); // HTTP GET request to the server and parse the response. HttpResponseMessage response = await client.GetAsync(url); string jsonString = await response.Content.ReadAsStringAsync(); T responseData = JsonConvert.DeserializeObject <T>(jsonString); return(responseData); } }
public async Task ProxiedRequest_DefaultPort_PortStrippedOffInUri(string host) { string addressUri = $"http://{host}:80/"; string expectedAddressUri = $"http://{host}/"; bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.Proxy = new WebProxy(proxyUri); try { await client.GetAsync(addressUri); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { connectionAccepted = true; List <string> headers = await connection.ReadRequestHeaderAndSendResponseAsync(); Assert.Contains($"GET {expectedAddressUri} HTTP/1.1", headers); })); Assert.True(connectionAccepted); }
public IActionResult Edit(int id) { Student student = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:44374/api/Students"); //HTTP GET var responseTask = client.GetAsync("Students?id=" + id.ToString()); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsAsync <Student>(); readTask.Wait(); student = readTask.Result; } } return(View()); }
public async Task ReturnsNotFoundWithoutWwwroot() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .ConfigureServices(services => services.AddSingleton(LoggerFactory)) .UseKestrel() .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) .Configure(app => app.UseStaticFiles()); }).Build(); await host.StartAsync(); using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { var response = await client.GetAsync("TestDocument.txt"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } }
private static Student GetStudentInformation(int studentId) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(SettingsHelper.GetSetting("ApiUri")); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync($"api/student?id={studentId}").Result; if (response.IsSuccessStatusCode) { var dataObjects = response.GetBodyFromJsonAsync <Student>().Result; return(dataObjects); } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } return(null); }
// GET: ProductsController public async Task <IActionResult> Index(int categoryId = 1) { var categories = await GetCategoriesAsync(); ViewBag.categoryId = new SelectList(categories, "categoryId", "categoryName"); var products = new List <Product>(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(baseURL); var response = await client.GetAsync($"products/ByCategory/{categoryId}"); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); products = JsonSerializer.Deserialize <List <Product> >(json); } } return(View(products)); }
/// <summary> /// This method checks the adhoc refill details /// </summary> /// <param name="order"></param> /// <param name="Token"></param> /// <returns></returns> public virtual dynamic requestAdhocRefill(RefillOrderLine order, string Token) { RefillDetails detail = ls.Where(x => x.Member_ID == order.Member_ID).FirstOrDefault(); Uri baseAddress = new Uri("http://52.154.215.101/api/Drugs/GetDrugDetails/" + detail.DrugID); HttpClient client = new HttpClient(); client.BaseAddress = baseAddress; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token); HttpResponseMessage response = client.GetAsync(client.BaseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; Drug s = JsonConvert.DeserializeObject <Drug>(data); if (s.drugLocation.Location == order.Location) { return(detail); } return("Unavailable"); } return(null); }
public async void GetMany_UserRequestsAnotherPartiesInstances_Ok() { // Arrange string requestUri = $"{BasePath}?instanceOwner.PartyId=1600"; HttpClient client = GetTestClient(); string token = PrincipalUtil.GetToken(3, 1337); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); int expectedNoInstances = 2; // Act HttpResponseMessage response = await client.GetAsync(requestUri); string json = await response.Content.ReadAsStringAsync(); InstanceQueryResponse queryResponse = JsonConvert.DeserializeObject <InstanceQueryResponse>(json); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedNoInstances, queryResponse.TotalHits); }
private static async Task<string> GetAsync(string url) { var client = new HttpClient(); var response = await client.GetAsync(new Uri(url)); var result = await response.Content.ReadAsStringAsync(); return result; }
private async static void UriSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { Debug.WriteLine("我被触发了"); StorageCachedImage image = d as StorageCachedImage; string i = e.NewValue as string; int k = i.IndexOf("image"); string imagePath = i.Substring(k + 7); string uri = App.Uri + "public/images/" + imagePath; Debug.WriteLine(uri); Uri imageUri = new Uri(uri); HttpClient client = new HttpClient(); var response = await client.GetAsync(imageUri); var buffer = await response.Content.ReadAsBufferAsync(); var memoryStream = new InMemoryRandomAccessStream(); await memoryStream.WriteAsync(buffer); await memoryStream.FlushAsync(); await image.SetSourceAsync(memoryStream); }