NOAA 最近将他们的服务从 http 切换到 https,并且已经工作多年的 ac# 调用现在返回“远程服务器返回错误:(403) Forbidden。”
奇怪的是,浏览器和 Postman 都可以使用相同的调用。为什么服务器会拒绝一个请求而不是另一个请求,我错过了什么?
根据下面接受的答案修改了示例代码。两个版本都没有设置 UserAgent,显然现在需要这样做:
string xml = "";
string url = "";
try
{
using (System.Net.WebClient wc = new System.Net.WebClient())
{
url = "https://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?zipCodeList=44113&product=time-series&begin=2017-03-23T00:00:00&temp=temp&appt=appt&pop12=pop12";
wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 1.1.4322; .NET CLR 3.5.20404)");
xml = wc.DownloadString(new Uri(url));
}
//......
}
catch (Exception ex)
{
LogError(ex);
}
或这个
string xml = "";
string url = "";
url = "https://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?zipCodeList=44113&product=time-series&begin=2017-03-23T00:00:00&temp=temp&appt=appt&pop12=pop12";
HttpWebRequest httpWR = (HttpWebRequest)WebRequest.Create(url);
httpWR.Method = WebRequestMethods.Http.Get;
httpWR.Accept = "application/xml";
httpWR.UserAgent = ".NET Framework Client";
try
{
using (HttpWebResponse response = (HttpWebResponse)httpWR.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
xml = reader.ReadToEnd();
}
}
//......
}
catch (Exception ex)
{
LogError(ex);
}