2010-11-15 199 views
2

我試圖從一個網站用c#下載一個XML文件,但我在一些網址上得到了404。這是有線的,因爲他們仍然在瀏覽器中工作。其他網址仍然沒有問題。C#HttpWebRequest顯示404,但網站是可以在瀏覽器

HttpWebRequest request = (HttpWebRequest) 
      WebRequest.Create(url); 
     request.Method = "GET"; 
     request.Timeout = 3000; 
     request.UserAgent = "Test Client"; 
     HttpWebResponse response = null; 
      try 
      { 
       response = (HttpWebResponse) 
        request.GetResponse(); 
      } 
      catch (WebException e) 
      { 
       response = (HttpWebResponse)e.Response; 
      } 
      Console.WriteLine("- "+response.StatusCode); 

     XmlTextReader reader = XmlTextReader(response.GetResponseStream()); 

此URL是說問題的其中一個網址:

http://numerique.bibliotheque.toulouse.fr/cgi-bin/oaiserver?verb=ListMetadataFormats 

解決....忘了修剪的URL;)

+0

某些服務器驗證用戶代理。嘗試使用一個真正的。 – 2010-11-15 20:23:44

+0

服務器可能正在查看User-Agent標頭或有關請求的其他詳細信息。 – driis 2010-11-15 20:25:09

+0

@Tom,你的代碼適合我。你有其他問題的URI嗎? – acoolaum 2010-11-15 20:40:12

回答

3

我只能猜測,主持人現場可能不喜歡你的UserAgent並返回一個404的消息

0

也許

1)s omehow您輸入的網址不正確:您可以嘗試 把

WebRequest.Create(@"http://numerique.bibliotheque.toulouse.fr/cgi-bin/oaiserver?verb=ListMetadataFormats"); 

,而不是

WebRequest.Create(url); 

用於測試目的。

2)你有一些這VS區分HTTP過濾機制&瀏覽器requrests

+0

是的,那@做的伎倆,ty – tom 2010-11-15 20:50:41

+0

我同意@ivo s問題可能在代理中,它想要授權... – acoolaum 2010-11-15 20:51:40

1

要下載XML文檔可以使用DownloadString方法:

System.Net.WebClient client = new System.Net.WebClient(); 

String url = "http://stackoverflow.com/feeds/question/4188449"; 

String xmlSource = client.DownloadString(url); 

Console.WriteLine(xmlSource); 
2

我用這個解決了這個問題:

var client = (HttpWebRequest)WebRequest.Create(uri); 
client.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; 
client.CookieContainer = new CookieContainer(); 
client.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; 
var htmlCodae = client.GetResponse() as HttpWebResponse; 
相關問題