当前位置:编程学习 > asp >>

【.Net MF网络开发板研究-03】获取雅虎天气

 

在上篇文章介绍了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);

                    }

     

补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,