Search code examples
c#httpwebrequestwebresponse

Webrequest Webresponse getting 403: forbidden


I'm trying to get some more experience with c# so I want to make a small app using windows forms in Visual Studio. The app should get rocket launch times from https://launchlibrary.net and use them in a countdown. I have no experience in getting data from the internet using c#, so I have no idea if what I'm doing is even slightly right. But this is the code I came up with after some research.

// 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();

The problem is that at the line:

WebResponse response = request.GetResponse();

I'm getting the below error

"The remote server returned an error (403) forbidden"


Solution

  • This is sample using WebClient, you must set the user-agent header, otherwise 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);
    }