作业要求
- 使用HttpWebRequest或HttpClient访问网络
- 输入城市查天气,快递查询等生活实用功能至少完成一种
- 自行上网查找API(不可与Demo相同!)
- Bonus:完成两种不同的API,且分别为JSON和XML格式
准备工作
选择管理方案的Nuget程序包
搜索httpclient,并安装
具体实现
先给一个粉红少女系的截图,解析Json得到温度,解析Xml得到PM2.5
再给一个文件目录
MainPage.xaml
<Page
x:Class="week7.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:week7"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="HotPink">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<Button x:Name="JsonsearchWeather" Content="Json查询天气" Click="searchWeather_Click"></Button>
<TextBox x:Name="JsonlocationInput" Text="北京" Height="50" Width="200"></TextBox>
<TextBox x:Name="JsonweatherResult" Text="hello weather" Height="50" Width="200"></TextBox>
</StackPanel>
<StackPanel Grid.Row="1">
<Button x:Name="XmlsearchWeather" Content="Xml查询天气" Click="XmlsearchWeather_Click"></Button>
<TextBox x:Name="XmllocationInput" Text="北京" Height="50" Width="200"></TextBox>
<TextBox x:Name="XmlweatherResult" Text="hello weather" Height="50" Width="200"></TextBox>
</StackPanel>
</Grid>
</Page>
MainPage.xmal.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net;
using System.Net.Http;
using week7;
// https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板
namespace week7
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void searchWeather_Click(object sender, RoutedEventArgs e)
{
try
{
RootObject myWeather = await OpenWeatherMapProxy.GetWeather(JsonlocationInput.Text);
JsonweatherResult.Text = myWeather.results[0].location.name + "的温度是" + myWeather.results[0].now.temperature;
}
catch
{
}
}
private async void XmlsearchWeather_Click(object sender, RoutedEventArgs e)
{
try
{
var XmlmyWeather = await xmlway.GetWe