【问题标题】:XmlReader Error in reading RSS Feed读取 RSS 提要时出现 XmlReader 错误
【发布时间】:2014-06-27 20:36:46
【问题描述】:

我正在尝试使用以下代码从http://backend.deviantart.com/rss.xml?q=gallery:duster132/23316533&type=deviation 读取 RSS 提要:

        //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 处可以正常工作。

我应该如何解决这个问题?

【问题讨论】:

    标签: c# rss xmlreader rss-reader


    【解决方案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));
    

    【讨论】:

    • 哇……好用!!!你能解释一下为什么这段代码有效吗?我查找了用户代理,但不确定我是否完全理解这一点。我已经被这个难住了好几个星期了……非常感谢!!!
    • @ChrisL 我不知道该怎么解释(用我有限的英语)。只需删除 wc.Headers 行并尝试。它不会工作......我是怎么找到它的?也许经验。
    • 如果我尝试使用以下内容加载 RSS xml,会有什么不同:XDocument rsslink = XDocument.Load(weblink);
    • @ChrisL 很可能XDocument.Load 不会发布User-Agent 标头。这不是必须的,但某些网站可能需要它。 (w3.org/Protocols/HTTP/HTRQ_Headers.html#user-agent)
    【解决方案2】:

    在我的例子中,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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-06
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 2012-03-04
      • 2016-06-01
      相关资源
      最近更新 更多