MAUI.NET MAUI – Calling RESTFUL API
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
-
微信小程序没声音怎么办
PHP中文网 06-15 -
excel图片置于文字下方的方法
PHP中文网 06-27 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
微信人名旁边有个图标有什么用
PHP中文网 03-11 -
微信提示登录环境异常是什么意思原因
PHP中文网 04-09 -
微信获取用户openid失败怎么办
PHP中文网 03-26 -
photoshop怎么把印章抠出并放在另一张图上
PHP中文网 06-15 -
EhViewer(E绅士)最新版_ehviewer白色版彩色版_Ehviewer显示网络错误怎么办?e站进不去了怎么办
Evanpatchouli 09-19 -
Excel筛选和排序是灰色的怎么办
PHP中文网 06-22 -
photoshop蒙版画笔没反应怎么办
PHP中文网 06-24