• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

MAUI.NET MAUI – Calling RESTFUL API

武飞扬头像
厦门德仔
帮助5

Calling RESTFUL API

学新通
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.

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfbkeef
系列文章
更多 icon
同类精品
更多 icon
继续加载