2

NOAA 最近将他们的服务从 http 切换到 https,并且已经工作多年的 ac# 调用现在返回“远程服务器返回错误:(403) Forbidden。”

奇怪的是,浏览器和 Postman 都可以使用相同的调用。为什么服务器会拒绝一个请求而不是另一个请求,我错过了什么?

网址: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

根据下面接受的答案修改了示例代码。两个版本都没有设置 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);
}
4

1 回答 1

3

我认为该服务需要一个有效的用户代理。

我已经修改了您的代码以包含它。

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(url);
        }
于 2017-03-23T18:54:17.893 回答