Api returns 通过 webrequest 调用时出现 403 错误,但在 postman 中调用时有效

Api returns 403 error when calling through webrequest, but works when calling in postman

我可以成功 运行 来自 Postman 的以下 OpenStreetMap api:
https://nominatim.openstreetmap.org/reverse?format=json&lat=30.32736&lon=56.91912

邮递员请求:

GET /reverse?format=json& lat=30.32736& lon=56.91912 HTTP/1.1
Host: nominatim.openstreetmap.org
cache-control: no-cache
Postman-Token: 92646056-107c-4011-b35f-85858ec715bd

但是当尝试使用此代码在 c# 中调用它时:

            HttpWebRequest objRequest = (HttpWebRequest)WebRequest
            .Create("https://nominatim.openstreetmap.org/reverse?format=json&lat=30.32736&lon=56.91912");
            objRequest.Method = "GET";
            objRequest.Headers.Add("User-Agent: Other");

            WebResponse response = (WebResponse)objRequest.GetResponse();
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            string result = "";
            using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
            {
                result = responseStream.ReadToEnd();
                responseStream.Close();
            }

我收到以下错误:

System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'

在线:

HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

经过搜索,我发现以下 header 建议添加到请求中:

objRequest.Headers.Add("User-Agent: SomeName");

但还是不行。

实际上,当我 运行 你的代码时,我得到一个 ArgumentException "The 'User-Agent' header must be modified using the appropriate property or method."

删除该行也会产生 403 错误。但是,您已经在正确的轨道上:将 objRequest.Headers.Add("User-Agent: SomeName"); 行替换为:

objRequest.UserAgent = "SomeName";

然后,它对我来说很好。