2009-10-24 74 views
2

我想在C#控制檯應用程序中使用HttpWebRequest讀取遠程文件。但由於某種原因,該請求爲空 - 它永遠不會找到該URL。閱讀遠程文件[C#]

這是我的代碼:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://uo.neverlandsreborn.org:8000/botticus/status.ecl"); 
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

爲什麼這是不可能的?

該文件只包含一個字符串。而已!

+1

網絡創世紀...是啊! – 2009-10-24 14:14:58

回答

12

你是如何讀取響應數據的?它是否成功返回,但爲空,還是有錯誤狀態?

如果這沒有幫助,請嘗試Wireshark,這可以讓您看到網絡層發生了什麼。

而且,考慮使用的WebClient代替WebRequest - 它使得它非常容易,當你不需要做任何事情複雜:

string url = "http://uo.neverlandsreborn.org:8000/botticus/status.ecl"; 
WebClient wc = new WebClient(); 
string data = wc.DownloadString(url); 
+0

... +1將我介紹給一個新班級。 – 2009-10-24 14:15:35

+0

嗯,由於某種原因服務器返回協議錯誤。這很奇怪!馬修斯的回答也一樣。 – janhartmann 2009-10-24 14:22:10

+0

什麼樣的協議錯誤?你有任何細節?用Wireshark來看看它發送的內容與瀏覽器發送的內容。 – 2009-10-24 14:27:36

3

您必須獲取響應流並從中讀取數據。下面是我爲一個項目寫的功能,它可以做到這一點:

private static string GetUrl(string url) 
    { 
     HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); 
     using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
     { 
      if (response.StatusCode != HttpStatusCode.OK) 
       throw new ServerException("Server returned an error code (" + ((int)response.StatusCode).ToString() + 
        ") while trying to retrieve a new key: " + response.StatusDescription); 

      using (var sr = new StreamReader(response.GetResponseStream())) 
      { 
       return sr.ReadToEnd(); 
      } 
     } 
    } 
+2

您也應該在使用說明中加上回應。 (根據一般原則,我也試着不首先聲明變量) – 2009-10-24 14:14:05

+0

+1兩個計數...分割定義是從實現後將其重構爲單獨函數的歷史工件我在幾個地方複製/粘貼了這段代碼。 – 2009-10-24 14:16:43