public async Task <IEnumerable <Books> > GetAllBooksAsync() { var requestUrl = "https://localhost:44382/api/Books/GetAll"; var response = await _httpProvider.GetAsync(requestUrl); var responseData = await response.Content.ReadAsStringAsync(); var books = JsonConvert.DeserializeObject <IEnumerable <Books> >(responseData); return(books); }
private string GetRawHtml() { _logger.LogDebug($"{nameof(GetRawHtml)} is being executed"); var requestUrl = FormatUrl(_request); return(_httpClientProvider.GetAsync(requestUrl).GetAwaiter().GetResult()); }
//[OutputCache(Duration = 10)] public async Task <ActionResult> RegisterSensor() { var resp = await httpClient.GetAsync(AppConstants.AllSensorsUrl); var content = await resp.Content.ReadAsStringAsync(); var resViewModel = JsonConvert.DeserializeObject <List <SensorApiData> >(content); foreach (var sensor in resViewModel) { var isValueType = !sensor.Description.Contains("false"); sensor.IsValueType = isValueType; if (isValueType) { var splitted = sensor.Description. Split(new string[] { "and", }, StringSplitOptions.RemoveEmptyEntries); var lowest = splitted[0].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Last(); var highest = splitted[splitted.Length - 1]; sensor.LowestValue = double.Parse(lowest); sensor.Highestvalue = double.Parse(highest); } } return(this.View(resViewModel)); }
// Fortnite tracker solo,duo and squad stats fortnitetracker.com public async Task <FortniteTrackerApi.Stats> GetStats(string id) { FortniteTrackerData data = new FortniteTrackerData(); var header = _clientProvider.GetHttpClientHeader(); header.Clear(); header.Add("TRN-Api-Key", TrnApiKey); var response = await _clientProvider.GetAsync(FortniteTrackerEndpoint + id); if (response.IsSuccessStatusCode) { data = JsonConvert.DeserializeObject <FortniteTrackerData>( await response.Content.ReadAsStringAsync()); } return(data.stats); }
private async Task <Guid> GetArtistId(string artistName) { var urlEncodedArtistName = HttpUtility.UrlEncode(artistName); // No pagination added here var response = await httpClientProvider.GetAsync($"https://musicbrainz.org/ws/2/artist?query={urlEncodedArtistName}&fmt=json&limit=100"); var responseString = await response.Content.ReadAsStringAsync(); var responseModel = JsonSerializer.Deserialize <GetArtistsResponseModel>(responseString, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (!responseModel.Artists?.Any() ?? true) { throw new InvalidOperationException($"Could not find any artist matching name: {artistName}"); } var artists = responseModel.Artists; if (artists.Count > 1) { artists = artists.OrderByDescending(x => x.Score).ToList(); var maxScore = artists.Select(y => y.Score).Max(); var ambiguousArtists = artists.Where(x => x.Score == maxScore).ToList(); if (ambiguousArtists.Count() > 1) { var message = new StringBuilder(); message.AppendLine("Could not determine exact artist name match. Best matches are:"); foreach (var artist in ambiguousArtists) { message.AppendLine(artist.Name); } throw new InvalidOperationException(message.ToString()); } } return(artists.First().Id); }
public async Task <IActionResult> Get() { var products = await _httpClient.GetAsync <List <ProductViewModel> >("https://localhost:44333", "api/products?v=1.0"); if (products is null) { return(BadRequest()); } return(Ok(products)); }
public async Task UpdateSensors() { var sensorsForUpdate = this.context.Sensors .Where(s => (DbFunctions.AddSeconds(s.LastUpdate, s.PollingInterval) <= DateTime.Now)) .ToList(); foreach (Sensor s in sensorsForUpdate) { var url = s.URL; var resp = await httpClient.GetAsync(url); var content = await resp.Content.ReadAsStringAsync(); var updatedValue = JsonConvert.DeserializeObject <SensorApiUpdate>(content); int pollingInterval = s.PollingInterval; if (s.IsBoolType) { if (s.BoolTypeSensor.CurrentValue != bool.Parse(updatedValue.Value)) { var valueHistory = new ValueHistory() { BoolSensor = s.BoolTypeSensor, Date = updatedValue.TimeStamp, Value = updatedValue.Value.ToLower() == "true" ? 1 : 0 }; s.BoolTypeSensor.BoolHistory.Add(valueHistory); s.BoolTypeSensor.CurrentValue = bool.Parse(updatedValue.Value); } } else { if (s.ValueTypeSensor.CurrentValue != double.Parse(updatedValue.Value)) { var valueHistory = new ValueHistory() { ValueSensor = s.ValueTypeSensor, Date = updatedValue.TimeStamp, Value = double.Parse(updatedValue.Value) }; s.ValueTypeSensor.ValueHistory.Add(valueHistory); s.ValueTypeSensor.CurrentValue = double.Parse(updatedValue.Value); SendEmailIfNeeded(s); } } s.LastUpdate = updatedValue.TimeStamp; } this.context.SaveChanges(); }
public async Task <string> GetNameFromID(string id) { var header = _clientProvider.GetHttpClientHeader(); //Define Headers header.Accept.Clear(); header.Accept.Add(_clientProvider.GetNewMTVQHeaderValue("application/json")); header.Authorization = _clientProvider.GetAuthenticationHeaderValue("bearer", (await GetToken()).access_token); //Request data var request = await _clientProvider.GetAsync(playerIdEndpoint + id); var a = JsonConvert.DeserializeObject <NameAndID[]>(await request.Content.ReadAsStringAsync()); return(a[0].DisplayName); }
private async Task <decimal> ObterTaxaDeJurosApiOneAsync() { try { var requestUri = _configuration.GetSection("UrlApiOneBase").Value + "api/v1/taxajuros"; var response = await _httpClientProvider.GetAsync(requestUri); var responseBody = await response.Content.ReadAsStringAsync(); CultureInfo usCulture = new CultureInfo("en-US"); var juros = Convert.ToDecimal(responseBody.Replace(",", ".").Trim(), usCulture); return(Math.Round(juros, 2)); } catch (HttpRequestException) { return(0); } }
/// <summary> /// Method in char of send request to SWAPI /// </summary> /// <param name="page">Number of page of SWAPI</param> /// <returns>Response of SWAPI </returns> public async Task <AllStarShipsResponse> GetAllStarShipsAsync(string page) { AllStarShipsResponse result; try { HttpResponseMessage response = await _httpClientProvider.GetAsync($"{GetAllStarShipsUrlByPage}{page}"); var stringResponse = await response.Content.ReadAsStringAsync(); var parsedResponse = JsonConvert.DeserializeObject <AllStarShipsResponse>(stringResponse); result = parsedResponse; } catch (Exception ex) { throw ex; } return(result); }
private async Task <HttpResponseMessage> GetLyricsWithRetry(string urlEncodedArtistName, string urlEncodedRecordingTitle) { var retryCount = 0; while (retryCount < 3) { try { var response = await httpClientProvider.GetAsync($"https://api.lyrics.ovh/v1/{urlEncodedArtistName}/{urlEncodedRecordingTitle}"); return(response); } catch { } retryCount++; await Task.Delay(2000); } return(null); }