当我尝试从URL导入XML时无法正常工作

时间:2020-01-11 22:51:25

标签: c# xml

努力获取 XML 进行导入,不断获取

403错误

作为一个基础,我是否编码盲目并将其拉错?

当我转到http://musicbrainz.org/ws/2/artist/?query=artist:coldplay时,此方法有效。

但是我尝试了以下代码并获得了

403错误

我尝试了其他一些操作,但是以下代码基于https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/querying-an-xdocument-vs-querying-an-xelement

var url = "http://musicbrainz.org/ws/2/artist/?query=artist:coldplay%20AND%20type:group%20AND%20country:GB";

XDocument doc = XDocument.Load(url);

IEnumerable <XElement> childList =
    from el in doc.Elements()
    select el;

foreach (XElement e in childList)
    Console.WriteLine(e); 

另外,我也尝试过:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://musicbrainz.org/ws/2/artist/?query=artist:coldplay");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

1 个答案:

答案 0 :(得分:2)

在您的情况下,看来服务器was expecting you to set a UserAgent header才可以获取xml:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://musicbrainz.org/ws/2/artist/?query=artist:coldplay");    
request.UserAgent = "My Super Script";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();  


XDocument doc = XDocument.Load(response.GetResponseStream());

IEnumerable<XElement> childList =
    from el in doc.Elements()
    select el;

foreach (XElement e in childList)
    Console.WriteLine(e);

在此处详细了解其API:https://musicbrainz.org/doc/Development/XML_Web_Service/Version_2