2016-07-06 161 views
0

我試圖讓一些更多的經驗與C#所以我想在Visual Studio中使用Windows窗體的小應用程序。該應用程序應該從https://launchlibrary.net獲得火箭發射時間並將其用於倒計時。 我沒有使用c#從互聯網獲取數據的經驗,所以我不知道我在做什麼甚至稍微正確。但這是我經過一番研究後提出的代碼。c#Webrequest Web響應獲取403:禁止

的問題是,在該行:WebResponse response = request.GetResponse();

我得到以下錯誤 -

「遠程服務器返回禁止錯誤(403)」

如果有人可以幫助我,也可以指向正確的方向,我會很高興。

謝謝

  // Create a request for the URL. 
      WebRequest request = WebRequest.Create("https://launchlibrary.net/1.2/agency/5"); 
      request.Method = "GET"; 
      // Get the response. 
      WebResponse response = request.GetResponse(); 
      // Display the status. 
      MessageBox.Show(((HttpWebResponse)response).StatusDescription); 
      // Get the stream containing content returned by the server. 
      Stream dataStream = response.GetResponseStream(); 
      // Open the stream using a StreamReader for easy access. 
      StreamReader reader = new StreamReader(dataStream); 
      // Read the content. 
      string responseFromTheServer = reader.ReadToEnd(); 
      // Display the content 
      MessageBox.Show(responseFromTheServer); 
      // Clean up the streams and the response. 
      reader.Close(); 
      response.Close(); 

回答

1

這是通過使用Web客戶端樣本,必須設置的用戶代理報頭,否則403:

using (var webClient = new WebClient()) 
{ 
    webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"); 
    var response = webClient.DownloadString("https://launchlibrary.net/1.2/agency/5"); 
    MessageBox.Show(response); 
} 
+0

謝謝。它現在正在工作 – Nickcap

+0

如果你讓用戶代理爲空,那麼你會得到403.這就是爲什麼我總是從chrome或firefox或IE使用user-agent。 – 2016-07-06 11:38:15