• C#实现中国天气网XML接口测试


    点击链接查看中国天气网接口说明,最近想研究一下接口测试,源于最近一次和某公司的技术总监(交大校友)谈话,发现接口测试的需求是比较大的,于是想要研究一下。

    好不容易在网上找到了一个关于中国天气网的接口说明,就是上面那篇。决定访问下这个接口,对接口返回的内容进行分析,筛选出我想要的信息。

    想到当时问及的接口主要是json类型的,但是苦于没有找到json类型的接口(上文中的json接口貌似失效了),就先拿xml类型的接口试验一下,我想原理应该都差不多,只是具体的实现有些不同。

    若谁有可用的json接口方便透漏一下,欢迎留言,非常感谢!

    以下以从中国天气网接口返回的内容中获取关于北京城市的天气信息举例,代码如下:

    using System;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Xml.Linq;
    
    namespace InterfaceTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                ReportWeather("北京");
            }
    
            private static void ReportWeather(string cityName)
            {
                string localContent = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"	est.txt";
                try
                {
                    string url = "http://flash.weather.com.cn/wmaps/xml/china.xml";
                    WebClient MyWebClient = new WebClient();
                    Byte[] pageData = MyWebClient.DownloadData(url); 
                    string pageHtml = Encoding.UTF8.GetString(pageData);
    //XDocument doc = XDocument.Parse(pageHtml); using (StreamWriter sw = new StreamWriter(localContent)) { sw.WriteLine(pageHtml); } XDocument doc = XDocument.Parse(pageHtml); //XDocument doc = XDocument.Load(localContent); var results = from ele in doc.Descendants("city") where ele.Attribute("cityname").Value.Equals(cityName) select ele; foreach (var result in results) { Console.WriteLine("城市:" + cityName); Console.WriteLine("天气情况:" + result.Attribute("stateDetailed").Value); Console.WriteLine("气温情况(摄氏度):" + result.Attribute("tem1").Value + "" + result.Attribute("tem2").Value); Console.WriteLine("风力情况:" + result.Attribute("windState").Value); } Console.ReadLine(); } catch (WebException webEx) { Console.WriteLine(webEx.Message.ToString()); } } } }

    不管是不是为了方便起见,我把接口返回的信息保存到了本地一份(路径为localContent),内容如下:

    运行截图如下(多云转霾……记得小时候听天气预报都是多云转晴……唉……):

    这样我们就实现了对xml接口返回信息的过滤,对于xml类型接口的测试。

  • 相关阅读:
    第十一周课程总结
    第十周课程总结
    第九周课程总结&实验报告(七)
    第八周课程总结&实验报告(六)
    第七周课程总结&实验报告(五)
    第六周课程总结&试验报告(四)
    课程总结
    第十四周课程总结&实验报告(简单记事本的实现)
    第十三周
    第十二周学习总结
  • 原文地址:https://www.cnblogs.com/LanTianYou/p/5042207.html
Copyright © 2020-2023  润新知