我试图获得更多的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) 禁止访问"
这是使用 WebClient 的示例,您必须设置用户代理标头,否则为 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);
}
在使用WebRequest从GoogleAPI获取纬度和经度时遇到了同样的问题,在@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;
}