用WPF技术搭建简单的气象免费小控件,注册取得key
前端代码:
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="611*"/> <ColumnDefinition Width="189*"/> </Grid.ColumnDefinitions> <StackPanel Margin="10,10,10,10" Grid.ColumnSpan="2"> <TextBlock Text="输入城市:"/> <TextBox x:Name="txtCity" Width="200"/> <Button Width="200" Content="取得天气" Click="btnGetWeather_Click" Margin="0,10,10,10"/> <TextBlock Text="气象信息:" Margin="0,20,0,0" /> <TextBlock x:Name="txtqixiangxinxi"/> </StackPanel> </Grid>View Code
后端逻辑
public partial class MainWindow : Window { private const string ApiKey = "key"; private const string ApiBaseUrl = "https://api.openweathermap.org/data/2.5/weather"; public MainWindow() { InitializeComponent(); } private async void btnGetWeather_Click(object sender, RoutedEventArgs e) { string city = txtCity.Text; string apiUrl = $"{ApiBaseUrl}?q={city}&appid={ApiKey}"; try { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.GetAsync(apiUrl); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); // 解析 JSON 数据,提取天气信息 // 这里需要根据您选择的 API 和其返回的数据结构进行解析 // 示例:从 OpenWeatherMap API 中提取温度信息 dynamic weatherData = JsonConvert.DeserializeObject(responseBody); double temperature = weatherData.main.temp - 273.15; // 转换为摄氏度 txtqixiangxinxi.Text = $"Temperature in {city}: {temperature}°C"; } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } } }View Code
Weather Conditions - OpenWeatherMap
标签:city,string,private,MainWindow,API,信息,response,气象 From: https://www.cnblogs.com/shiningleo007/p/18051978