public async Task <JObject> GetCurrentWeather(double lat, double lon) { var weatherApiKey = _config["WeatherApiKey"]; Uri uri = new Uri($"{_config["WeatherBaseUri"]}lat={lat}&lon={lon}&appid={_config["WeatherApiKey"]}"); var response = await _httpHandler.GetAsync(uri); return(await GetJsonFromHttpResponse(response)); }
/* * It's good practice to keep these requests asynchronous. .NET uses * async/await just like ES2017. */ public async Task <string> GetData(string baseUrl) { //The 'using' will help to prevent memory leaks //Create a new instance of HttpClient IHttpClientHandler client = _httpClient; //Setting up the response... using (HttpResponseMessage res = await client.GetAsync(baseUrl)) try { Console.WriteLine("Starting here before expection"); using (HttpContent content = res.Content) { string data = await content.ReadAsStringAsync(); if (data != null) { Console.WriteLine(data); return(data); } else { Console.WriteLine("no data"); return("err no data"); } } } catch (Exception e) { return("err no content"); } }
public Task <IAsset> GetAssets() { var assets = _httpClientHandler.GetAsync <AssetInfo>(PuplicApiUrl); //use mapper for map to Global asset type throw new NotImplementedException(); }
/// <summary> /// Gets a page of the list of starships /// </summary> /// <param name="page">The page.</param> /// <returns>A page result with a list of starships</returns> private PageResult <StarshipDTO> Get(string page) { PageResult <StarshipDTO> model = null; var task = _httpClientHandler.GetAsync(page) .ContinueWith((taskResponse) => { var a = taskResponse.Result; var response = a.Content.ReadAsStringAsync(); response.Wait(); model = JsonConvert.DeserializeObject <PageResult <StarshipDTO> >(response.Result); }); task.Wait(); return(model); }
/// <summary> /// This will retrieve data from an external api asynchronously /// </summary> /// <param name="url">Where to get the data from</param> /// <typeparam name="T">The data retrieved will be deserialized into this object type</typeparam> /// <returns>The data from the GET external api endpoint</returns> public async Task <T> GetApiAsync <T>(string url) { try { HttpResponseMessage response = await _httpClient.GetAsync(url); if (response.IsSuccessStatusCode) { var resultAsString = await response.Content.ReadAsStringAsync(); return(JsonSerializer.Deserialize <T>(resultAsString)); } } catch (Exception ex) { Console.WriteLine($"Exception in ApiAccessHelper. Message: {ex.Message}"); } return(default(T)); }
protected async Task <T> GetResponseAndDeserialize <T>(string url) { var response = await _httpClient.GetAsync(url); if (!response.IsSuccessStatusCode) { throw new ThirdPartyApiUnreachableException($"Failed to communicate with {url}: {response.ReasonPhrase}"); } try { var content = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <T>(content)); } catch (JsonSerializationException ex) { throw new JsonSerializationException($"failed to deserialize the response of the {url}", ex); } }
public override async Task <List <ResourceDTO> > Search(string searchText) { string urlSearch = "https://yandex.com/search/xml" + $"?user={UserName}" + $"&key={SubscriptionKey}" + $"&query={searchText}" + "&l10n=en&sortby=tm.order%3Dascending&filter=none&groupby=attr%3Dd.mode%3Ddeep.groups-on-page%3D10.docs-in-group%3D3"; var httpResponseMessage = await _client.GetAsync(urlSearch); if (!httpResponseMessage.IsSuccessStatusCode) { throw new Exception($"{nameof(YandexCustomSeacher)} doesn't work"); } var responseContent = httpResponseMessage.Content.ReadAsStringAsync().Result; XDocument xmlResponse = XDocument.Parse(responseContent); List <ResourceDTO> dataModel = new List <ResourceDTO>(); XElement results = xmlResponse.Descendants("grouping").SingleOrDefault(); if (results == null) { throw new Exception($"{nameof(YandexCustomSeacher)} doesn't find anything"); } foreach (XElement phoneElement in results.Elements("group")) { XElement url = phoneElement.Element("doc").Element("url"); XElement title = phoneElement.Element("doc").Element("title"); XElement description = phoneElement.Element("doc").Element("headline"); dataModel.Add(new ResourceDTO() { UrlAddress = url?.Value, Title = title?.Value, Description = description?.Value }); } return(dataModel); }
private async Task UpdateRecordInRedisAsync(LastChangedRecord record, RedisStore redisStore, CancellationToken cancellationToken) { var requestUrl = GetBaseUri(record.Uri) + record.Uri; using var response = await _httpClient.GetAsync(requestUrl, record.AcceptType ?? "application/json", cancellationToken); var responseStatusCode = (int)response.StatusCode; if (await HasInvalidStatusCode(record, redisStore, responseStatusCode, requestUrl, response)) { return; } if (await EligibleForDeletion(record, redisStore, responseStatusCode, requestUrl, response)) { return; } var responseContent = await response.Content.ReadAsStringAsync(cancellationToken); var responseHeaders = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase); foreach (var headerToStore in _headersToStore.Concat(new[] { HeaderNames.ETag })) { var headerName = headerToStore.ToLowerInvariant(); if (response.Headers.TryGetValues(headerName, out var headerValues)) { responseHeaders.Add(headerName, headerValues.ToArray()); } } await redisStore.SetAsync( record.CacheKey?.ToLowerInvariant(), responseContent, responseStatusCode, responseHeaders, record.Position); record.LastPopulatedPosition = record.Position; }
public override async Task <List <ResourceDTO> > Search(string searchText) { var url = "https://api.bing.microsoft.com/v7.0/custom/search" + $"?q={searchText}" + $"&customconfig={ConfigID}" + $"&mkt=en-US"; _client.AddHeaders("Ocp-Apim-Subscription-Key", SubscriptionKey); var httpResponseMessage = await _client.GetAsync(url); if (!httpResponseMessage.IsSuccessStatusCode) { throw new Exception($"{nameof(BingCustomSeacher)} doesn't work"); } var responseContent = httpResponseMessage.Content.ReadAsStringAsync().Result; BingCustomSearchResponse response = JsonConvert.DeserializeObject <BingCustomSearchResponse>(responseContent); if (response.webPages == null) { throw new Exception($"{nameof(YandexCustomSeacher)} doesn't find anything"); } List <ResourceDTO> resources = new List <ResourceDTO>(); for (int i = 0; i < response.webPages.value.Length; i++) { var webPage = response.webPages.value[i]; resources.Add(new ResourceDTO { UrlAddress = webPage.url, Title = webPage.name, Description = webPage.snippet }); } return(resources); }
private async Task UpdateRecordInRedisAsync(LastChangedRecord record, RedisStore redisStore, CancellationToken cancellationToken) { var requestUrl = _apiBaseAddress + record.Uri; using (var response = await _httpClient.GetAsync(requestUrl, record.AcceptType, cancellationToken)) { var responseStatusCode = (int)response.StatusCode; if (await HasInvalidStatusCode(record, redisStore, responseStatusCode, requestUrl, response)) { return; } if (await EligibleForDeletion(record, redisStore, responseStatusCode, requestUrl, response)) { return; } var responseContent = await response.Content.ReadAsStringAsync(); var responseHeaders = new Dictionary <string, string[]>(); foreach (var headerToStore in _headersToStore) { var headerName = headerToStore.ToLowerInvariant(); if (response.Headers.TryGetValues(headerName, out var headerValues)) { responseHeaders.Add(headerName, headerValues.ToArray()); } } await redisStore.SetAsync( record.CacheKey.ToLowerInvariant(), responseContent, responseStatusCode, responseHeaders); record.LastPopulatedPosition = record.Position; } }
public async Task <SPIndexDTO> GetMarketStackIndexes(string marketStackIndexProviderUrl, HttpHeaderSetting httpHeaderSetting) { using (var response = await _httpClientHandler.GetAsync(marketStackIndexProviderUrl)) { _httpClientHandler.SetHttpHeaderSettings(httpHeaderSetting); var stream = await _streamHandler.ReadAsStreamAsync(response); if (response.IsSuccessStatusCode) { return(await _streamHandler.DeserializeJsonFromStreamAsync <SPIndexDTO>(stream)); } var content = await _streamHandler.StreamToStringAsync(stream); throw new ApiException { StatusCode = (int)response.StatusCode, Content = content }; } }