使用WebRequest下載xml數據!

今天幫一個同事做了個小程序,他的要求是: 要取一個論壇的帖子的標題,然後在他的網站裏面把這些標題顯示出來。由於已經有數據源,所以也不難,但是要要我直接通過Url去取這些xml格式的數據,我首先想到了使用XmlTextReader這個xml讀取類來讀取xml數據,因爲這個操作類正好支持從url取數據的功能,但是,等我實際操作的時候,報了一個錯,錯誤消息爲:讀取gbk格式的xml出錯,我馬上查了一下,發現XmlTextReader不能讀取gbk格式的xml數據,這就鬱悶了,因爲想這樣子的話就需要我對這些gbk編碼的xml數據進行解碼,但是能夠支持解碼的xml操作類好像又不支持從url取數據的功能(目前我沒發現,有誰知道的就告訴我一聲),最後我就想到使用WebRequest去下載這些xml數據,然後在流中對這些gbk編碼的xml數據進行轉碼,最後我終於搞出來了,代碼如下:(注意:使用了代理上網的人一定記得在調用下載方法的時候要傳入自己的代理設置,否則會下載失敗)

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Net;
using System.IO;
using System.Text;

namespace myTest
{
    
/// <summary>
    
/// WebForm1 的摘要說明。
    
/// </summary>

    public class WebForm1 : System.Web.UI.Page
    
{
        
//protected static Hashtable hs = new Hashtable();
        private void Page_Load(object sender, System.EventArgs e)
        
{
            
this.Init_Data();
        }


        
Web 窗體設計器生成的代碼

        
private void Init_Data()
        
{
            
string result = string.Empty;
            System.Xml.XmlDocument doc 
= new XmlDocument();
            
string url = "http://bbs.foshan.gov.cn/rss.php?fid=53&auth=0";
            
string proxy = "test.gmcc.net:8006"//這是我的代理地址,你如果沒有使用代理就設置爲空
            
//到緩存中取xml數據,如果緩存中沒有數據則執行下載方法
            if (Cache["xmlData"!= null)
            
{
                doc.LoadXml((
string)Cache["xmlData"]);
                Response.Write(
"<font color='red'>從緩存中取</font>");
            }

            
else
            
{
                
//開始下載數據
                string strXml = this.DownLoad(url,proxy);
                
//緩存xml數據,不用每次都去下載(每隔30秒就更新一次緩存中的數據)
                Cache.Insert("xmlData",strXml,null,DateTime.Now.AddSeconds(30),TimeSpan.Zero,System.Web.Caching.CacheItemPriority.Normal,null);
                doc.LoadXml(strXml);
                Response.Write(
"<font color='blue'>下載的數據</font>");
            }

            
//StreamReader reader = new StreamReader(@"c:.xml",System.Text.Encoding.Default);

            System.Xml.XmlNodeList nodes 
= doc.SelectNodes("//title[position()>0]"); //只需取標題就可以了
            foreach (System.Xml.XmlNode node in nodes)
            
{
                result 
+= node.InnerText;
            }

            Response.Write(result);
            Response.End();
        }


        
/// <summary>
        
/// 下載xml數據方法
        
/// </summary>
        
/// <param name="Url">要下載的xml地址</param>
        
/// <param name="MyProxy">如果設置了代理,就設置;如果沒有則傳空字符串</param>
        
/// <returns>返回下載到的xml數據</returns>

        public string DownLoad(string Url,string MyProxy)
        
{
            
string strResult = "";
            Uri u 
= new Uri(Url);

            HttpWebRequest myReq 
= (HttpWebRequest)WebRequest.Create(u);
            myReq.Timeout 
= 3600 * 1000 * 2;
            
if (MyProxy != "" & MyProxy != ":")
            
{
                WebProxy proxyObject 
= new WebProxy(MyProxy, true);
                myReq.Proxy 
= proxyObject;
            }


            
try
            
{
                HttpWebResponse HttpWResp 
= (HttpWebResponse)myReq.GetResponse();
                myReq.AllowAutoRedirect 
= false;

                Stream myStream 
= HttpWResp.GetResponseStream();
                
//在流中進行轉碼
                StreamReader sr = new StreamReader(myStream, Encoding.Default);

                Char[] read 
= new Char[256];

                
int count = sr.Read(read, 0256);
                
while (count > 0)
                
{
                    
//把 流中的數據讀取完畢
                    strResult += new String(read, 0, count);
                    count 
= sr.Read(read, 0256);
                }

                sr.Close();
                myStream.Close();
                HttpWResp.Close();
                myReq.Abort();
            }

            
catch (Exception exp)
            
{
                
throw new Exception("錯誤:" + exp.Message);
            }

            
return strResult;
        }

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章