-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathWeatherStackClient.cs
More file actions
81 lines (70 loc) · 2.87 KB
/
WeatherStackClient.cs
File metadata and controls
81 lines (70 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace PrimeHotel.Web.Clients
{
public class WeatherStackClient : IWeatherStackClient
{
private const string ApiKey = "3a1223ae4a4e14277e657f6729cfbdef";
private const string Username = "Mik";
private const string Password = "****";
private const string WeatherStackUrl = "http://api.weatherstack.com/current";
private HttpClient _client;
private readonly ILogger<WeatherStackClient> _logger;
public WeatherStackClient(HttpClient client, ILogger<WeatherStackClient> logger)
{
_client = client;
_logger = logger;
// authorization is not needed to call WeatherStack.com - this is only to show how to add basic authorization
var authToken = Encoding.ASCII.GetBytes($"{Username}:{Password}");
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(authToken));
}
public async Task<WeatherStackResponse> GetCurrentWeather(string city)
{
try
{
using var responseStream = await _client.GetStreamAsync(GetWeatherStackUrl(city));
var currentForecast = await JsonSerializer.DeserializeAsync<WeatherStackResponse>(responseStream);
return currentForecast;
}
catch (Exception e)
{
_logger.LogError(e, $"Something went wrong when calling WeatherStack.com");
return null;
}
}
public async Task<WeatherStackResponse> GetCurrentWeatherWithCancellationToken(string city)
{
try
{
using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3));
using var responseStream = await _client.GetStreamAsync(GetWeatherStackUrl(city), cancellationTokenSource.Token);
var currentForecast = await JsonSerializer.DeserializeAsync<WeatherStackResponse>(responseStream);
return currentForecast;
}
catch (TaskCanceledException ec)
{
_logger.LogError(ec, $"Call to WeatherStack.com took longer then 3 seconds and had timed out ");
return null;
}
catch (Exception e)
{
_logger.LogError(e, $"Something went wrong when calling WeatherStack.com");
return null;
}
}
private string GetWeatherStackUrl(string city)
{
return WeatherStackUrl + "?"
+ "access_key=" + ApiKey
+ "&query=" + city;
}
}
}