C# 无法从URL读取XML-远程服务器返回错误:(403)禁止
我试图使用下面的代码使用API URL读取XML(即,我试图避免下载它)C# 无法从URL读取XML-远程服务器返回错误:(403)禁止,c#,.net,C#,.net,我试图使用下面的代码使用API URL读取XML(即,我试图避免下载它) using System; using System.Xml; class SampleXMLTest { private void ReadXMLUsingURL_Test1() { log("#1"); XmlDocument doc; XmlNamespaceManager ns; XmlNodeList nodes;
using System;
using System.Xml;
class SampleXMLTest
{
private void ReadXMLUsingURL_Test1()
{
log("#1");
XmlDocument doc;
XmlNamespaceManager ns;
XmlNodeList nodes;
// Create a new XmlDocument
doc = new XmlDocument();
// Load data
doc.Load("http://apps.someurl.int/rest/collection/10000?expand=items&limit=100&offset=1400");
log("#2");
// Set up namespace manager for XPath
ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace(string.Empty, http://apps.someurl.int/rest/collection/10000?expand=items&limit=100&offset=1400");
log("#3");
// Get forecast with XPath
nodes = doc.SelectNodes("/collection/items", ns);
log("#4");
foreach (XmlNode node in nodes)
log("<handle>:" + node.Attributes("handle").InnerText + vbtab + "<id>:" + node.Attributes("id").InnerText);
}
private void ReadXMLUsingURL_Test2()
{
log("#1");
XmlNamespaceManager ns;
XmlNodeList nodes;
var m_strFilePath = "http://apps.someurl.int/rest/collection/10000?expand=items&limit=100&offset=1400";
string xmlStr;
using (var wc = new WebClient())
{
xmlStr = wc.DownloadString(m_strFilePath);
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
log("#2");
// Set up namespace manager for XPath
ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace(string.Empty, "http://apps.someurl.int/rest/collection/10000?expand=items");
log("#3");
// Get forecast with XPath
nodes = doc.SelectNodes("/collection/items", ns);
log("#4");
foreach (XmlNode node in nodes)
log("<handle>:" + node.Attributes["handle"].InnerText + vbtab + "<id>:" + node.Attributes["id"].InnerText);
}
private void log(string msg)
{
Console.WriteLine(msg);
}
}
您可以尝试添加以下代码:
doc = new XmlDocument();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://apps.someurl.int/rest/collection/10000&limit=100&offset=100");
request.UserAgent = "My User Agent";
// Load data
doc.Load(request.GetResponse().GetResponseStream());
问题是由于doc.Load未发送用户代理,导致服务器认为它是一个bot/脚本。您可以尝试添加以下代码:
doc = new XmlDocument();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://apps.someurl.int/rest/collection/10000&limit=100&offset=100");
request.UserAgent = "My User Agent";
// Load data
doc.Load(request.GetResponse().GetResponseStream());
问题是由于doc.Load未发送用户代理,导致服务器认为它是一个bot/脚本