繁体   English   中英

REST服务已切换为https,可在浏览器中运行,并在C#中引发“(403)Forbidden”错误

[英]REST service switched to https, works in browser, throwing a “(403) Forbidden” error in c#

NOAA最近将其服务从http切换为https,并且已经使用了多年的ac#调用现在返回“远程服务器返回错误:(403)禁止访问”。

奇怪的是,同一呼叫可以从浏览器和Postman进行。 为什么服务器拒绝一个请求而不拒绝另一个请求,我丢失了什么?

网址: https//graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?zipCodeList = 44113&product = time-series&begin = 2017-03-23T00: 0000&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);
}

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

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

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);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM