从装载URL XML时超时错误 [英] Timeout error when loading Xml from URL
问题描述
我做加载实时XML文件(活URL)来的XmlDataDocument的任务,但每次我得到错误时间:
I am doing task of loading the live xml file (from live url) to XmlDataDocument, but every time I am getting error:
该操作已超时
在code是如下,包含XML的URL饲料,我希望将其加载到xmlDoc中。
The code is as follows, The url containing the xml feeds , I want to load it into xmlDoc.
XmlDataDocument xmlDoc = new XmlDataDocument();
xmlDoc.Load("http://www.globalgear.com.au/productfeed.xml");
请提出任何解决办法。
推荐答案
不要使用直接的XmlDataDocument类的Load方法;你几乎没有办法影响的行为,当涉及到长时间运行的HTTP请求。
Don't use the Load method of the XmlDataDocument class directly; you have little to no way of influencing the behaviour when it comes to long running HTTP requests.
相反,使用HttpWebRequest和HttpWebResponse类做的工作给你,然后加载后续响应到文档中。
Instead, use the HttpWebRequest and HttpWebResponse classes to do the work for you, and then load the subsequent response into your document.
例如:
HttpWebRequest rq = WebRequest.Create("http://www.globalgear.com.au/productfeed.xml") as HttpWebRequest;
//60 Second Timeout
rq.Timeout = 60000;
//Also note you can set the Proxy property here if required; sometimes it is, especially if you are behind a firewall - rq.Proxy = new WebProxy("proxy_address");
HttpWebResponse response = rq.GetResponse() as HttpWebResponse;
XmlTextReader reader = new XmlTextReader(response.GetResponseStream());
XmlDocument doc = new XmlDocument();
doc.Load(reader);
我测试过这个code在本地的应用程序实例和XmlDocument的填充了从您的网址中的数据。
I've tested this code in a local app instance and the XmlDocument is populated with the data from your URL.
您也可以在替换为的XmlDataDocument的XmlDocument在上面的例子 - 我preFER使用XmlDocument的,因为它不是(还)标记为已过时。
You can also substitute in XmlDataDocument for XmlDocument in the example above - I prefer to use XmlDocument as it's not (yet) marked as obsolete.
我在一个函数包装这个给你:
I've wrapped this in a function for you:
public XmlDocument GetDataFromUrl(string url)
{
XmlDocument urlData = new XmlDocument();
HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(url);
rq.Timeout = 60000;
HttpWebResponse response = rq.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(responseStream);
urlData.Load(reader);
}
return urlData;
}
要获取使用:
XmlDocument document = GetDataFromUrl("http://www.globalgear.com.au/productfeed.xml");
这篇关于从装载URL XML时超时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!