使用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;
        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值