【MAUI】.NET MAUI – Calling RESTFUL API

Calling RESTFUL API

【MAUI】.NET MAUI – Calling RESTFUL API_第1张图片
This tutorial will show you how to make a RESTful API call in .NET MAUI.

Microsoft Visual Studio Community 2022 (64-bit) - Preview
Version 17.1.0 Preview 2.0
Microsoft .NET Framework Version 4.8.09014
The purpose of this app is to show current weather of your location by latitude and longitude.
On .NET MAUI – Enabling Geolocation, we were able to get the device’s location.

I’ll be using API from OpenWeather – Current Weather Data, and make sure that you get the API key from your account.

Once you have the API key, let’s store the key in Maui.Essentials’ Preferences class. In App.xaml.cs, add this line below.

Preferences.Set(“WeatherAPIKey”, “YOURAPIKEY”);

It’s a good idea to make a Model that matches the response of the API’s response. We will deserialize the JSON format to the model object.

public class WeatherDTO
    {
        public Coord Coord { get; set; }
        public List<Weather> Weather { get; set; }
        public string Base { get; set; }
        public Main Main { get; set; }
        public int Visibility { get; set; }
        public Wind Wind { get; set; }
        public Clouds Clouds { get; set; }
        public int Dt { get; set; }
        public int Timezone { get; set; }
        public int Id { get; set; }
        public string Name { get; set; }
        public int Cod { get; set; }
    }

    public class Coord
    {
        public double Lon { get; set; }
        public double Lat { get; set; }
    }
    public class Weather
    {
        public int Id { get; set; }
        public string Main { get; set; }
        public string Description { get; set; }
        public string Icon { get; set; }
    }
    public class Main
    {
        public double Temp { get; set; }
        public double Feels_like { get; set; }
        public double Temp_min { get; set; }
        public double Temp_max { get; set; }
        public int Pressure { get; set; }
        public int Humidity { get; set; }
    }
    public class Wind
    {
        public double Speed { get; set; }
        public int Deg { get; set; }
    }
    public class Clouds
    {
        public double All { get; set; }
    }
    public class Sys
    {
        public int Type { get; set; }
        public int Id { get; set; }
        public double Message { get; set; }
        public string Country { get; set; }
        public int Sunrise { get; set; }
        public int Sunset { get; set; }
    }

Now it’s time to create the method that calls and handles the API call.

private async void CallWeatherAPI()
    {
		LocationDTO locationDTO = await GetLocation();
		string apiKey = Preferences.Get("WeatherAPIKey", "");

		string URL = "https://api.openweathermap.org/data/2.5/weather?lat=" + locationDTO.Latitude + "&lon=" + locationDTO.Longitude + "&appid=" + apiKey + "&units=metric";

		HttpClient client = new HttpClient();

		client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

		HttpResponseMessage response = client.GetAsync(URL).Result;

        if (response.IsSuccessStatusCode)
        {
			HttpContent content = response.Content;
			string result = await content.ReadAsStringAsync();

			var weatherDTO = JsonConvert.DeserializeObject<WeatherDTO>(result);

			WeatherIcon.Source = "https://openweathermap.org/img/wn/" + weatherDTO.Weather[0].Icon + "@2x.png";
			DescriptionLabel.Text = weatherDTO.Weather[0].Main;
			CityLabel.Text = weatherDTO.Name;
			TemperatureLabel.Text = "Temperature: " + weatherDTO.Main.Temp.ToString() + "℃";
			FeelsLikeLabel.Text = "Feels like " + weatherDTO.Main.Feels_like.ToString() + "℃";
		}
		else
		{
			Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
		}
	}

To retrieve the API key that we stored in App.xaml.cs, you can simply call Preferences.Get(“KeyName”, “Default value if not found”)
For JsonConvert class, make sure you install Newtonsoft.Json in NugetPackage.

 <Image
                x:Name="WeatherIcon"
                Grid.Row="2"
                GridLayout.ColumnSpan="2"
                HorizontalOptions="FillAndExpand"
                VerticalOptions="FillAndExpand" />
            <Label
                x:Name="DescriptionLabel"
                Grid.Row="3"
                GridLayout.ColumnSpan="2"
                HorizontalOptions="Center"
                Text="Description" />
            <Label
                x:Name="CityLabel"
                Grid.Row="4"
                FontAttributes="Bold"
                FontSize="30"
                GridLayout.ColumnSpan="2"
                HorizontalOptions="Center"
                Text="City Name"
                TextColor="DarkSlateGray"
                VerticalTextAlignment="Start" />
            <Label
                x:Name="TemperatureLabel"
                Grid.Row="5"
                Grid.Column="0"
                FontAttributes="Bold"
                FontSize="18"
                HorizontalOptions="Center"
                Text="Temperature" />
            <Label
                x:Name="FeelsLikeLabel"
                Grid.Row="5"
                Grid.Column="1"
                FontAttributes="Bold"
                FontSize="18"
                HorizontalOptions="Center"
                Text="FeelsLike" />

Done!! Now you should be able to get your weather information based on your device’s coordinate.

【MAUI】.NET MAUI – Calling RESTFUL API_第2张图片

你可能感兴趣的:(#,MAUI,.net,restful,java,API)