我尝试从特定站点获取特定值...
站点使用 Ajax 调用定期更新值 https://www.plus500.co.il/api/LiveData/FeedUpdate?instrumentId=19
(您可以导航到该地址并查看您获得的 XML 响应。)
使用 postman : 发送
GET /api/LiveData/FeedUpdate?instrumentId=19 HTTP/1.1
Host: www.plus500.co.il
Cache-Control: no-cache
Postman-Token: f823c87d-3edc-68ce-e1e7-02a8fc68be7a
我得到一个有效的 Json 响应...
不过,当我从 C# 尝试时:
var webRequest = WebRequest.CreateHttp(@"https://www.plus500.co.il/api/LiveData/FeedUpdate?instrumentId=19");
webRequest.Method = "GET";
using (var response = webRequest.GetResponse())
{...}
请求失败,错误代码为 403(禁止访问)
添加时:
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36";
请求失败,错误代码为 500(内部服务器错误)
添加(编辑)
我也发起
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls |
SecurityProtocolType.Ssl3;
此外,我尝试设置一个 CookieContainer,但结果仍然是 500。
为什么 Postman/Chrome 可以成功查询此 API 而 C# Webrequest 没有?
有什么区别?
最佳答案
因此,失败的原因是默认情况下, header 包含在 postman 的客户端请求中,尽管不是来自 C# 请求。
使用像 Fiddler (https://www.telerik.com/fiddler) 这样的程序,您可以查看请求以查看 postman 请求的 header 是:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36
然而来自 C# 只是
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
像这样填写额外的客户端请求 header 可以让它顺利通过:
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
webRequest.Headers.Add("Accept-Encoding", "gzip deflate,br");
webRequest.Headers.Add("Accept-Language", "en-US,en;q=0.9");
关于c# - Web Http 请求失败 (500) 而 postman 成功运行 Web GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51753391/