zoukankan      html  css  js  c++  java
  • 【.Net MF网络开发板研究03】获取雅虎天气(HttpClient示例)

          在上篇文章介绍了Http Server,通过PC上的IE浏览器(相当于Http client)来访问开发板上的Http服务。这次我们在网络开发板上实现Http Client,获取雅虎网站的天气信息,并把这些信息在LCD上显示出来。

          包含两部分的代码,一是通过Http协议获取数据,二是对获取的网页,进行XML解析,以期获取天气信息。

          主程序很简单,就是web服务请求和画面显示。

           public static void Main()

            {

                try

                {

                    weather = new yahooWeatherRequest();

                    weather.webRequest();

                }

                catch

                {

                    Debug.Print("Error!");

                }

                WindowsDrawing win = new WindowsDrawing();

                win.Width = SystemMetrics.ScreenWidth;

                win.Height = SystemMetrics.ScreenHeight;

                new Program().Run(win);

            }

          创建Http请求,并获取数据,相关代码如下:

          private byte[] getHttpData(string url)

            {

                HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

                request.HttpsAuthentCerts = null;

                request.KeepAlive = true;

                WebResponse resp = null;

                Stream respStream = null;

                byte[] bytData = null;

                try

                {

                    resp = request.GetResponse();

                }

                catch (Exception e)

                {

                    Debug.Print("Exception in HttpWebRequest.GetResponse(): " + e.Message.ToString());

                    return null;

                }

     

                if (resp != null)

                {

                    respStream = resp.GetResponseStream();

                    int bytesRead = 0;

                    int totalBytes = 0;

                    respStream.ReadTimeout = 5000;

                    Debug.Print("resp length= " + resp.ContentLength.ToString());

                    if (resp.ContentLength!=-1)

                    {

                        bytData = new byte[resp.ContentLength];

                        while (totalBytes < bytData.Length)

                        {

                             bytesRead = respStream.Read(bytData, totalBytes, bytData.Length - totalBytes);

                             if (bytesRead == 0)

                             {

                                 Debug.Print("Error: Received " + totalBytes.ToString() + " Out of " + bytData.Length.ToString());

                                 bytData = null;

                                 break;

                             }

                             totalBytes += bytesRead;

                             Debug.Print("Bytes Read Now 0: " + bytesRead + " Total: " + totalBytes);

                        }

                        return bytData;

                    }

                  

                }

                if (respStream != null) respStream.Close();

                if (resp != null) resp.Close();

                request = null;

                return bytData;

            }

            数据获取后,进行必要的XML解析,以提取天气数据。

            private void parseRssPage(byte[] rssPage)

            {

                MemoryStream mStream = new MemoryStream(rssPage);

                XmlReader xReader = XmlReader.Create(mStream);

                forcastArray = new ArrayList();

                while (xReader.Read())

                {

                    if (xReader.NodeType == XmlNodeType.Element)

                    {

                        switch (xReader.Name)

                        {

                            case "title":

                                xReader.Read();

                                break;

                            case "pubDate":

                                xReader.Read();

                                break;

                            case "yweather:location":

                                myCity = new cityInfo(xReader.GetAttribute("city"), xReader.GetAttribute("region"), xReader.GetAttribute("country"));

                                break;

                            case "yweather:condition":

                                today = new todayCondition(xReader.GetAttribute("text"), xReader.GetAttribute("temp"), xReader.GetAttribute("date"));

                                 break;

                            case "yweather:forecast":

                                forcastArray.Add(new forcastCondition(xReader.GetAttribute("day"), xReader.GetAttribute("date"), xReader.GetAttribute("low"),

                                    xReader.GetAttribute("high"), xReader.GetAttribute("text")));

                                 break;

                        }

                    }

                    else if (xReader.NodeType == XmlNodeType.CDATA)

                        parseCDATA(xReader.Value);

                }

            }

            数据解析完毕后,就进行屏幕显示了。

                public override void OnRender(DrawingContext dc)

                {

                    dc.DrawRectangle(new SolidColorBrush(Colors.White), new Pen(Colors.White), 0, 0, Width, Height);

                    dc.DrawLine(new Pen(Colors.Gray), 10, 46, 310, 46);               dc.DrawImage(Resources.GetBitmap(Resources.BitmapResources.yahoo_news_wea), 10, 10);

                    if (Program.weather != null)

                    {

                        int Y = 60;

                        if (weather.MyCity != null) dc.DrawText(weather.MyCity.ToString(), Resources.GetFont(Resources.FontResources.small), Colors.Black, 10, Y);

                        if (weather.Today != null)

                        {

                            dc.DrawText(weather.Today.date, Resources.GetFont(Resources.FontResources.small), Colors.Black, 10, Y + 20);

                            dc.DrawText(weather.Today.weahterDesc + "   temperature: " + weather.Today.curTemp + "c", Resources.GetFont(Resources.FontResources.small), Colors.Black, 10, Y + 40);

                        }

                        dc.DrawText("Forcast -- this week:", Resources.GetFont(Resources.FontResources.small), Colors.Black, 10, Y + 80);

                        Y += 80;

                        if (weather.ForcastArray != null)

                        {

                            foreach (yahooWeatherRequest.forcastCondition forcast in weather.ForcastArray)

                            {

                                string info = forcast.date + " , " + forcast.day + " , " + forcast.weahterDesc + " , " + forcast.lowTemp + "c ~ " + forcast.highTemp + "c ";

                                Y += 20;

                                dc.DrawText(info, Resources.GetFont(Resources.FontResources.small), Colors.Black, 10, Y);

                            }

                        }

                    }

          保证开发板正确的接入互联网,注意设置好DNS服务器(这个事例也可以不用设置,不过如果测试官方的HttpClient事例,是一定要设置的,因为目前MF的LWIP协议栈不支持默认的DNS),运行程序,则在超级终端中,我们可以看到我们从互联网上请求的数据(如下图):

              

         开发板运行后的画面如下:

           

         开发板最新的固件版本:V0.9.06  下载地址:http://www.sky-walker.com.cn/MFRelease/firmware/mfv41_firmware_hy_redbull.rar

     ----------------------------------------------------------------------------------------------

    源码/文档:http://www.sky-walker.com.cn/MFRelease/Sample/YFHttpClient.rar

    MF快速入门:http://blog.csdn.net/yefanqiu/article/details/5340560

    MF论坛:http://space.cnblogs.com/group/MFSoft/

    MF开发板:http://item.taobao.com/item.htm?id=7117999726

    网络开发板:http://item.taobao.com/item.htm?id=10919470266

    QQ群:127465602(已满) 146524112

  • 相关阅读:
    移动开发学习touchmove
    webapp利用iscroll实现同时横滚|竖滚
    centos配置备忘(apachephpmysql)
    VMware ESXi 配置小结
    【C语言程序设计】C语言求自守数(详解版)
    世界500强企业面试题:猴子吃香蕉!这是人能想出来的答案?
    【C语言程序设计】C语言判断三角形的类型!
    拿什么来衡量程序员的生产力!代码量?开发速度?忙碌的状态?都不是!
    如果你拿到蚂蚁p7的offer,但是你正在国企拿着60+,你会如何选择?
    【C语言程序设计】汉诺塔问题,用C语言实现汉诺塔!
  • 原文地址:https://www.cnblogs.com/yefanqiu/p/2106915.html
Copyright © 2011-2022 走看看