2014-06-27 76 views
0

我試圖從http://backend.deviantart.com/rss.xml?q=gallery:duster132/23316533&type=deviation用下面的代碼讀取RSS提要:的XmlReader錯誤飼料

 //Different RSS Links 
     string deviant_rsslink = @"http://backend.deviantart.com/rss.xml?q=gallery:duster132/23316533&type=deviation"; 
     string blogspot_rsslink = @"http://fightpunch.blogspot.com/feeds/posts/default"; 

     //Reading the links 
     XmlReader reader = XmlReader.Create(deviant_rsslink); //LINE WHERE ERROR OCCURS 
     SyndicationFeed feed = SyndicationFeed.Load(reader); 
     reader.Close(); 
     foreach (SyndicationItem item in feed.Items) 
     { 
      String subject = item.Title.Text; 
      Console.WriteLine("Subjext is: " + subject + "\n"); 
     } 

...我得到的錯誤:

"The underlying connection was closed: The connection was closed unexpectedly." 

起初我認爲deviantart可能會阻止我的IP,所以我試圖從不同的IP不同的計算機,但錯誤仍然存​​在,所以它似乎不是問題。爲了使事情更難追蹤,代碼在http://fightpunch.blogspot.com/feeds/posts/default處無錯誤地工作。

我該如何解決這個問題?

回答

1

你的網站需要User-Agent頭被設置

下面的代碼應該工作..

string rss = null; 
using (var wc = new Webclient()) 
{ 
    wc.Headers["User-Agent"] = "SO/1.0"; 
    rss = wc.DownloadString(deviant_rsslink); 
} 
XmlReader reader = XmlReader.Create(new StringReader(rss)); 
+0

哇......那工作!你能解釋爲什麼這段代碼有效嗎?我查了一下用戶代理,但不知道我是否完全明白這一點。我已經被這個星期難住了......非常感謝你! –

+0

@ChrisL我不知道如何解釋它(用我有限的英語)。只要刪除'wc.Headers'行並嘗試。它不會工作...我是如何找到它的?也許經驗。 –

+0

如果我嘗試使用以下方法加載RSS xml,這將如何不同: XDocument rsslink = XDocument.Load(weblink); –

0

在我的情況SSL是殘疾人和TLS才被允許。我改爲使用HTTPWebRequest。請注意,我使用.NET 4.0,並沒有TLS1.2作爲選項,所以我硬編碼的值(3072)爲:

Dim doc As New XmlDocument() 
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(FeedAddress), HttpWebRequest) 
ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType) 
req.Method = "GET" 
Dim myHttpWebResponse As HttpWebResponse = DirectCast(req.GetResponse(), HttpWebResponse) 

Dim response As WebResponse = req.GetResponse 
Dim streamResponse As Stream = response.GetResponseStream 
doc.Load(streamResponse)