uwp网络访问

作业要求

  • 使用HttpWebRequest或HttpClient访问网络
  • 输入城市查天气,快递查询等生活实用功能至少完成一种
  • 自行上网查找API(不可与Demo相同!)
  • Bonus:完成两种不同的API,且分别为JSON和XML格式

准备工作

选择管理方案的Nuget程序包
Nuget
搜索httpclient,并安装
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.GetWeather(XmllocationInput.Text);
                XmlweatherResult.Text = XmlmyWeather.results.currentCity + "的PM2.5是 " + XmlmyWeather.results.pm25;
            }
            catch
            {

            }
        }
    }
}

OpenWeatherMapProxy.cs

这个类实现Json的解析

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace week7
{
        public class OpenWeatherMapProxy
        {
            public async static Task<RootObject> GetWeather(string location)
            {
            string link = "https://api.seniverse.com/v3/weather/now.json?key=pw0dibkghhvjjnc6&location=" + location + "&language=zh-Hans&unit=c";
                var http = new HttpClient();
            //var response = await http.GetAsync("https://api.seniverse.com/v3/weather/now.json?key=pw0dibkghhvjjnc6&location=beijing&language=zh-Hans&unit=c");
                var response = await http.GetAsync(link);
                var result = await response.Content.ReadAsStringAsync();
                var serializer = new DataContractJsonSerializer(typeof(RootObject));

                var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
                var data = (RootObject)serializer.ReadObject(ms);

            return data;
            }
        }

    [DataContract]
    public class Location
    {
        [DataMember]
        public string id { get; set; }
        /// <summary>
        /// 北京
        /// </summary>
        [DataMember]
        public string name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [DataMember]
        public string country { get; set; }
        /// <summary>
        /// 北京,北京,中国
        [DataMember]
        public string path { get; set; }
        /// <summary>
        /// 
        [DataMember]
        public string timezone { get; set; }
        /// <summary>
        /// 
        [DataMember]
        public string timezone_offset { get; set; }
    }
    [DataContract]
    public class Now
    {
        /// <summary>
        /// 多云
        [DataMember]
        public string text { get; set; }
        /// <summary>
        /// 
        [DataMember]
        public string code { get; set; }
        /// <summary>
        /// 
        [DataMember]
        public string temperature { get; set; }
    }
    [DataContract]
    public class ResultsItem
    {
        /// <summary>
        /// 
        [DataMember]
        public Location location { get; set; }
        /// <summary>
        /// 
        [DataMember]
        public Now now { get; set; }
        /// <summary>
        /// 
        [DataMember]
        public string last_update { get; set; }
    }
    [DataContract]
    public class RootObject
    {
        /// <summary>
        /// 
        [DataMember]
        public List<ResultsItem> results { get; set; }
    }
}

xmlway.cs

这个类实现Xml解析

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace week7
{
    public class xmlway
    {
        public async static Task<CityWeatherResponse> GetWeather(String Location)
        {
            string link = "http://api.map.baidu.com/telematics/v3/weather?location=" +Location +"&ak=8IoIaU655sQrs95uMWRWPDIa";
            var http = new HttpClient();
            //var response = await http.GetAsync("http://api.map.baidu.com/telematics/v3/weather?location=%E6%AD%A6%E6%B1%89&ak=8IoIaU655sQrs95uMWRWPDIa");
            var response = await http.GetAsync(link);
            var result = await response.Content.ReadAsStringAsync();
            var serializer = new XmlSerializer(typeof(CityWeatherResponse));

            var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
            var data = (CityWeatherResponse)serializer.Deserialize(ms);
            return data;
        }

        public class Weather_data
        {
            /// <summary>
            /// 
            /// </summary>
            public List<string> date { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> dayPictureUrl { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> nightPictureUrl { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> weather { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> wind { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> temperature { get; set; }
        }

        public class Index
        {
            /// <summary>
            /// 
            /// </summary>
            public List<string> title { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> zs { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> tipt { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<string> des { get; set; }
        }

        public class Results
        {
            /// <summary>
            /// 北京
            /// </summary>
            public string currentCity { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Weather_data weather_data { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Index index { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string pm25 { get; set; }
        }

        public class CityWeatherResponse
        {
            /// <summary>
            /// 
            /// </summary>
            public string error { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string status { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string date { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Results results { get; set; }
        }

        //public class Root
        //{
        //    /// <summary>
        //    /// 
        //    /// </summary>
        //    public CityWeatherResponse CityWeatherResponse { get; set; }
        //}
    }
}

解释OpenWeatherMapProxy.cs和xmlway.cs

我主要是反序列化Json和xml格式,生成一个class,解析Json都是正常的,解析xml的时候list<string>类型的值为空,不知道原因是什么,所以只得到了PM2.5,虽然可以用GetElementsByTagName,得到想要的变量,感觉那么写就不需要解析了,直接提取了。怎么得到对应Json和xml的类,可以先试一下这个链接测试返回值是Json,把里面的内容全部复制,然后进入Json转Class(似乎被墙了)这个网站,转换一下就OK了,xml也可以用上诉的网站转成Json格式,再用Json格式转成Class,等于几乎不用写代码。

更新与问题解决

先来一张粉嫩少女系的最新截图
最新截图
最新的版本解决了list<string>的问题,方法是把xml直接转成class,在这个网站可以直接转,xml转c#实体类

xmlway.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace week7
{
    public class xmlway
    {
        public async static Task<CityWeatherResponse> GetWeather(String Location)
        {
            string link = "http://api.map.baidu.com/telematics/v3/weather?location=" + Location + "&ak=8IoIaU655sQrs95uMWRWPDIa";
            var http = new HttpClient();
            //var response = await http.GetAsync("http://api.map.baidu.com/telematics/v3/weather?location=%E6%AD%A6%E6%B1%89&ak=8IoIaU655sQrs95uMWRWPDIa");
            var response = await http.GetAsync(link);
            var result = await response.Content.ReadAsStringAsync();
            var serializer = new XmlSerializer(typeof(CityWeatherResponse));

            var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
            var data = (CityWeatherResponse)serializer.Deserialize(ms);
            return data;
        }

    }

    [XmlRoot(ElementName = "weather_data")]
    public class Weather_data
    {
        [XmlElement(ElementName = "date")]
        public List<string> Date { get; set; }
        [XmlElement(ElementName = "dayPictureUrl")]
        public List<string> DayPictureUrl { get; set; }
        [XmlElement(ElementName = "nightPictureUrl")]
        public List<string> NightPictureUrl { get; set; }
        [XmlElement(ElementName = "weather")]
        public List<string> Weather { get; set; }
        [XmlElement(ElementName = "wind")]
        public List<string> Wind { get; set; }
        [XmlElement(ElementName = "temperature")]
        public List<string> Temperature { get; set; }
    }

    [XmlRoot(ElementName = "index")]
    public class Index
    {
        [XmlElement(ElementName = "title")]
        public List<string> Title { get; set; }
        [XmlElement(ElementName = "zs")]
        public List<string> Zs { get; set; }
        [XmlElement(ElementName = "tipt")]
        public List<string> Tipt { get; set; }
        [XmlElement(ElementName = "des")]
        public List<string> Des { get; set; }
    }

    [XmlRoot(ElementName = "results")]
    public class Results
    {
        [XmlElement(ElementName = "currentCity")]
        public string CurrentCity { get; set; }
        [XmlElement(ElementName = "weather_data")]
        public Weather_data Weather_data { get; set; }
        [XmlElement(ElementName = "index")]
        public Index Index { get; set; }
        [XmlElement(ElementName = "pm25")]
        public string Pm25 { get; set; }
    }

    [XmlRoot(ElementName = "CityWeatherResponse")]
    public class CityWeatherResponse
    {
        [XmlElement(ElementName = "error")]
        public string Error { get; set; }
        [XmlElement(ElementName = "status")]
        public string Status { get; set; }
        [XmlElement(ElementName = "date")]
        public string Date { get; set; }
        [XmlElement(ElementName = "results")]
        public Results Results { get; set; }
    }
}


教学视频

直接看这个网站就可以了

资源和演示视频

资源和演示视频

猜你喜欢

转载自blog.csdn.net/yaoxh6/article/details/80056321
UWP