我正在尝试使用c#获得更多经验,所以我想在Visual Studio中使用Windows窗体创建一个小应用程序。该应用程序应从https://launchlibrary.net获得火箭发射时间并在倒计时中使用它们。 我没有使用c#从互联网上获取数据的经验,所以我不知道我正在做的事情是否稍微正确。但这是我在经过一些研究后提出的代码。
// 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();
问题在于:
WebResponse response = request.GetResponse();
我收到以下错误
“远程服务器返回错误(403)禁止”
答案 0 :(得分:1)
这是使用WebClient的示例,您必须设置user-agent标头,否则设置为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);
}
答案 1 :(得分:0)
使用WebRequest从GoogleApis获取纬度和经度时,在@ user6522773的帮助下也遇到了相同的问题,我将代码修改为以下内容:
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;
}