[英]Api returns 403 error when calling through webrequest, but works when calling in postman
I can successfully run the following OpenStreetMap
api from Postman: 我可以从Postman成功运行以下OpenStreetMap
api:
https://nominatim.openstreetmap.org/reverse?format=json&lat=30.32736&lon=56.91912 https://nominatim.openstreetmap.org/reverse?format=json&lat=30.32736&lon=56.91912
Postman request: 邮递员要求:
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
But when trying to call it in c# using this code: 但是,当尝试使用以下代码在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();
}
I get the following error: 我收到以下错误:
System.Net.WebException: 'The remote server returned an error: (403) Forbidden.' System.Net.WebException:'远程服务器返回错误:(403)禁止。
On line: 在线:
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
After I did a search, I found the following header suggested to be added to the request: 搜索后,发现建议将以下标头添加到请求中:
objRequest.Headers.Add("User-Agent: SomeName");
But still not working. 但仍然无法正常工作。
Actually, when I run your code, I get an ArgumentException "The 'User-Agent' header must be modified using the appropriate property or method." 实际上,当我运行您的代码时,会收到ArgumentException“必须使用适当的属性或方法来修改'User-Agent'标头。”
Removing the line also yields the 403 error. 删除该行还会产生403错误。 But, you are already on the right track: Replace your objRequest.Headers.Add("User-Agent: SomeName");
但是,您已经在正确的轨道上:替换您的objRequest.Headers.Add("User-Agent: SomeName");
line with: 符合:
objRequest.UserAgent = "SomeName";
Then, it works fine for me. 然后,它对我来说很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.