2016-03-08 94 views
0

我想要的Atom提要加載到一個字符串,我使用下面的方法:HttpWebRequest的Atom的URL返回HTML內容

private string GetXml(string urlString) 
     { 
      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; 
      StringBuilder sb = new StringBuilder(); 
      // Create a new HttpWebRequest object.Make sure that 
      // a default proxy is set if you are behind a firewall. 
      HttpWebRequest myHttpWebRequest1 = 
       (HttpWebRequest)WebRequest.Create(urlString); 

      myHttpWebRequest1.KeepAlive = false; 
      myHttpWebRequest1.ContentType = "text/xml"; 
      // Assign the response object of HttpWebRequest to a HttpWebResponse variable. 
      HttpWebResponse myHttpWebResponse1 = 
       (HttpWebResponse)myHttpWebRequest1.GetResponse(); 

      Debug.WriteLine("\nThe HTTP request Headers for the first request are: \n{0}", myHttpWebRequest1.Headers); 

      Stream streamResponse = myHttpWebResponse1.GetResponseStream(); 
      StreamReader streamRead = new StreamReader(streamResponse); 
      Char[] readBuff = new Char[256]; 
      int count = streamRead.Read(readBuff, 0, 256); 
      Debug.WriteLine("The contents of the response are.......\n"); 
      while (count > 0) 
      { 
       String outputData = new String(readBuff, 0, count); 
       sb.Append(outputData); 
       count = streamRead.Read(readBuff, 0, 256); 
      } 
      // Close the Stream object. 
      streamResponse.Close(); 
      streamRead.Close(); 
      return sb.ToString(); 
     } 

這適用於大多數的飼料,但http://tipsforbbq.com/RSS,這使得作爲瀏覽器中的原子提要,返回一個HTML頁面(在http://tipsforbbq.com/處找到)。有誰知道爲什麼會發生這種情況?

+1

你有沒有綁定使用用戶代理,例如「Mozilla/5.0(Windows NT 6.1; WOW64; rv:40.0)Gecko/20100101 Firefox/40.1」? – ganchito55

+0

就是這樣!讓它成爲答案,我會標記它。謝謝! – Michael

+0

thanksssssssssssssssssssss – ganchito55

回答

2

我和HttpWebRequest有類似的問題,我用知名的用戶代理解決了這個問題。

myHttpWebRequest1.UserAgent= @"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1"; 

我希望這可以幫助你。

+0

更好的是,使用你自己的用戶代理而不是掩飾並提供一個Accept頭來告訴遠程服務你期望什麼類型的內容。 –