1

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"

ekad
  • 14,436
  • 26
  • 44
  • 46
Nickcap
  • 13
  • 1
  • 3

2 Answers2

1

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);
}
  • If you let user-agent empty, then you get 403. Thats why I use always user-agent from chrome or firefox or IE. –  Jul 06 '16 at 11:38
0

Had same problem when using WebRequest for getting Latitude and Longitude from GoogleApis, with the help of @user6522773 I modified my code to the following:

using (var webClient = new WebClient())
{
    string requestUri = $"http://maps.googleapis.com/maps/api/geocode/xml?address={Uri.EscapeDataString(address)}&sensor=false";
    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(requestUri);
    XDocument xdoc = XDocument.Parse(response);

    XElement result = xdoc.Element("GeocodeResponse").Element("result");
    XElement locationElement = result.Element("geometry").Element("location");
    XElement lat = locationElement.Element("lat");
    XElement lng = locationElement.Element("lng");
    MapPoint point = new MapPoint { Latitude = (double)lat, Longitude = (double)lng };
    return point;
}
u-ways
  • 6,136
  • 5
  • 31
  • 47
Usman Mahmood
  • 536
  • 4
  • 7