在移动开发过程中,第三方对接是非常常见的。今天给大家分享.NET MAUI如何使用REST API实现输入城市名称查询天气的示例,希望对大家学习.NET MAUI可以提供一些帮助!
一、接口准备首先我们需要找一个查询天气的API接口,这里使用 https://api.vvhan.com/api/weather?city=苏州 API接口进行获取实时天气的json数据,返回示例json如下:
{ "success": true, "city": "北京市", "data": { "date": "2024-08-16", "week": "星期五", "type": "中雨", "low": "24°C", "high": "31°C", "fengxiang": "西北风", "fengli": "1-3级", "night": { "type": "小雨", "fengxiang": "北风", "fengli": "1-3级" } }, "air": { "aqi": 35, "aqi_level": 1, "aqi_name": "优", "co": "1", "no2": "10", "o3": "109", "pm10": "30", "pm2.5": "21", "so2": "3" }, "tip": "现在的温度比较舒适~"}二、实体部分通过http请求获取json字符需要转换为实体对象,方便天气结果的拼接展示。首先我们根据接口返回示例创建实体。
新建HttpResponseModel.cs 文件
最外层json数据
public HttpResponseModel{ /// <summary> /// 是否成功 true false /// </summary> public bool success { get; set; } /// <summary> /// 城市 /// </summary> public string city { get; set; } /// <summary> /// 天气情况实体 /// </summary> public Data data { get; set; } /// <summary> /// 空气质量 /// </summary> public Air air { get; set; } /// <summary> /// 提示 /// </summary> public string tip { get; set; }}新建Night.cs 实体文件
定义傍晚预测的天气情况
public Night{ /// <summary> /// 晴 /// </summary> public string type { get; set; } /// <summary> /// 东风 /// </summary> public string fengxiang { get; set; } /// <summary> /// 1-3级 /// </summary> public string fengli { get; set; }}新建Data.cs 实体文件
定义实时的天气情况
public Data{ /// <summary> /// 日期 /// </summary> public string date { get; set; } /// <summary> /// 星期 /// </summary> public string week { get; set; } /// <summary> /// 天气 /// </summary> public string type { get; set; } /// <summary> /// 最低温度 /// </summary> public string low { get; set; } /// <summary> /// 最高温度 /// </summary> public string high { get; set; } /// <summary> /// 风向 /// </summary> public string fengxiang { get; set; } /// <summary> ///风力等级 /// </summary> public string fengli { get; set; } /// <summary> /// /// </summary> public Night night { get; set; }}新建Air.cs 实体文件
定义空气质量实体
/// <summary> /// 空气质量 /// </summary> public Air { /// <summary> /// /// </summary> public int aqi { get; set; } /// <summary> /// /// </summary> public int aqi_level { get; set; } /// <summary> /// 优 /// </summary> public string aqi_name { get; set; } /// <summary> /// /// </summary> public string co { get; set; } /// <summary> /// /// </summary> public string no2 { get; set; } /// <summary> /// /// </summary> public string o3 { get; set; } /// <summary> /// /// </summary> public string pm10 { get; set; } /// <summary> /// /// </summary> public string so2 { get; set; } }三、页面部分创建APP页面APIDemo.xaml,这里为了方便演示,创建一个Label用来展示查询的天气结果、一个输入框用来输入城市名称、一个查询按钮用来实现查询动作。
页面代码如下:
<?xml version="1.0" encoding="utf-8" ?><ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyFirstMauiApp.APIDemo" Title="APIDemo"> <VerticalStackLayout> <Label x:Name="Label1" Text="测试" VerticalOptions="Center" HorizontalOptions="Center" /> <Entry x:Name="entry" Text="北京" Placeholder="请输入城市" /> <Button x:Name="WeatherBtn" Clicked="OnWeatherClicked" Text="查询天气" HeightRequest="30" HorizontalOptions="Center" Margin="5" Style="{StaticResource ButtonStyle}" BorderWidth="1" TextColor="White" BackgroundColor="#2946E6" BorderColor="#2946E6" /> </VerticalStackLayout></ContentPage>四、后台代码逻辑APIDemo.xaml 页面的后台代码文件编写http请求函数和按钮事件绑定查询结果。这里使用官方自带的HttpClient请求类库和Json解析工具进行操作。
代码如下:
/// <summary> /// 发起http请求 获取天气json数据 /// </summary> /// <returns></returns> public async Task<HttpResponseModel> GetHttp() { var result = new HttpResponseModel(); HttpClient _client=new HttpClient(); string str = entry.Text; var options = new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString }; Uri uri = new Uri(string.Format(url+ "?city="+str, string.Empty)); try { HttpResponseMessage response = await _client.GetAsync(uri); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); result = JsonSerializer.Deserialize<HttpResponseModel>(content, options); } } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); } return result; } /// <summary> /// 查询天气按钮事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void OnWeatherClicked(object sender, EventArgs e) { var result = await GetHttp(); if (result.success) { StringBuilder sb=new StringBuilder(); sb.AppendLine("城市;"+result.city); sb.AppendLine("日期;"+result.data.date); sb.AppendLine("星期;" + result.data.week); sb.AppendLine("天气:" + result.data.type); string res=sb.ToString(); Label1.Text = sb.ToString(); } }运行效果
说明:
需要指定http请求的options:NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString,否则json解析的时候会出错。
按钮事件获取http请求需要加await关键字,因为是异步http请求,不加await关键字执行顺序会有问题。
五、总结以上只是一个简单的查询天气完整过程,大家可以参考写法进行封装。有问题的话可以评论区沟通交流!