WeatherService.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using MyWeather.Models;
  2. using System.Net.Http;
  3. using System.Threading.Tasks;
  4. using static Newtonsoft.Json.JsonConvert;
  5. namespace MyWeather.Services
  6. {
  7. public enum Units
  8. {
  9. Imperial,
  10. Metric
  11. }
  12. public class WeatherService
  13. {
  14. const string WeatherCoordinatesUri = "http://api.openweathermap.org/data/2.5/weather?lat={0}&lon={1}&units={2}&appid=fc9f6c524fc093759cd28d41fda89a1b";
  15. const string WeatherCityUri = "http://api.openweathermap.org/data/2.5/weather?q={0}&units={1}&appid=fc9f6c524fc093759cd28d41fda89a1b";
  16. const string ForecaseUri = "http://api.openweathermap.org/data/2.5/forecast?id={0}&units={1}&appid=fc9f6c524fc093759cd28d41fda89a1b";
  17. public async Task<WeatherRoot> GetWeather(double latitude, double longitude, Units units = Units.Imperial)
  18. {
  19. using (var client = new HttpClient())
  20. {
  21. var url = string.Format(WeatherCoordinatesUri, latitude, longitude, units.ToString().ToLower());
  22. var json = await client.GetStringAsync(url);
  23. if (string.IsNullOrWhiteSpace(json))
  24. return null;
  25. return DeserializeObject<WeatherRoot>(json);
  26. }
  27. }
  28. public async Task<WeatherRoot> GetWeather(string city, Units units = Units.Imperial)
  29. {
  30. using (var client = new HttpClient())
  31. {
  32. var url = string.Format(WeatherCityUri, city, units.ToString().ToLower());
  33. var json = await client.GetStringAsync(url);
  34. if (string.IsNullOrWhiteSpace(json))
  35. return null;
  36. return DeserializeObject<WeatherRoot>(json);
  37. }
  38. }
  39. public async Task<WeatherForecastRoot> GetForecast(int id, Units units = Units.Imperial)
  40. {
  41. using (var client = new HttpClient())
  42. {
  43. var url = string.Format(ForecaseUri, id, units.ToString().ToLower());
  44. var json = await client.GetStringAsync(url);
  45. if (string.IsNullOrWhiteSpace(json))
  46. return null;
  47. return DeserializeObject<WeatherForecastRoot>(json);
  48. }
  49. }
  50. }
  51. }