2013-02-18 61 views
0

我試圖使用'XMLTextReader'從RSS feed中提取數據。雖然它加載在Web瀏覽器完全正常,我得到一個400錯誤(「遠程服務器返回錯誤:(400)錯誤的請求」)當我用我的代碼:無法加載在瀏覽器中正常加載的C#rss feed(400錯誤)

XmlTextReader reader = new XmlTextReader(url); 
while (reader.Read()) 
{ //Do something } 

我也試過'WebClient'無濟於事。

任何人都可以啓發我爲什麼它在瀏覽器中工作,但不是與我的代碼請嗎?

P.S - 它正常工作與數據類似的格式一樣this

+0

你得到了什麼確切的錯誤? – 2013-02-18 14:56:26

+0

遠程服務器返回錯誤:(400)錯誤的請求。 – user1567095 2013-02-18 15:14:02

回答

1

Can anybody enlighten me as to why it works in a browser but not with my code please?

也許遠程網站希望您設置的UserAgent。例如:

using (var client = new WebClient()) 
{ 
    client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17"; 
    using (var stream = client.OpenRead(url)) 
    using (var reader = XmlReader.Create(stream)) 
    { 
     while (reader.Read()) 
     { 
      // ... 
     } 
    } 
} 

或者網站可能要求您進行身份驗證才能調用此資源?在這種情況下,您需要隨請求一起發送身份驗證Cookie。如果您不確定,請聯繫網站管理員以獲取有關如何使用API​​的更多信息。

哦,順便說一下,您爲.NET框架內置的SyndicationFeed類完全是爲了這個目的。使用XmlReader解析RSS似乎相當費力。

+0

謝謝你的幫助!原來是UserAgent的一部分。這是一項急需的工作,當我有時間學習時,它將升級爲SyndicationFeed。 – user1567095 2013-02-18 15:46:05

0

可能用WebClient下載它,並以這種方式將它提供給XmlTextReader?

var url = "http://marketplaceedgeservice.windowsphone.com/v8/catalog/apps/4aef0ee8-2378-e011-986b-78e7d1fa76f8?os=8.0.9903.0&cc=GB&oc=&lang=en-GB&hw=520170499&dm=RM-821_eu_euro1_111&oemId=NOKIA&moId=vod-gb&cf=99-1"; 
var data = ""; 

using (var wc = new WebClient()) 
{ 
    wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4"); 
    data = wc.DownloadString(url);     
} 

var reader = new XmlTextReader(new System.IO.StringReader(data)); 
while (reader.Read()) 
{ 
    // 
} 
+1

謝謝你的幫助! – user1567095 2013-02-18 15:44:57