var doc = XDocument.Load("https://www.predictit.org/api/marketdata/all");
Run Code Online (Sandbox Code Playgroud)
失败,但异常:
System.dll 中发生类型为“System.Net.WebException”的未处理异常
附加信息:基础连接已关闭:发送时发生意外错误。
即使您可以通过 chrome访问https://www.predictit.org/api/marketdata/all。
api 页面:https : //predictit.freshdesk.com/support/solutions/articles/12000001878-does-predictit-make-market-data-available-via-an-api- 提到将文本附加到请求头,可能是线索?
“要更改上述任何一项的返回类型,请将以下内容之一添加到请求标头中。
接受:应用程序/xml
接受:应用程序/json”
我检查了我的防火墙,两个网络都允许使用 Visual Studio。
对于该特定错误,它是由 TLS 握手错误引起的。您可以通过在代码中的某处添加以下内容来启用适当的 TLS 协议来修复它:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls
| System.Net.SecurityProtocolType.Tls11
| System.Net.SecurityProtocolType.Tls12;
Run Code Online (Sandbox Code Playgroud)
完成排序后,您将遇到其他响应问题。您必须在请求上设置接受标头。如果您尝试在没有标头的情况下下载,默认情况下它将返回 JSON。浏览器将包含 XML 作为标头之一,这就是您看到 XML 的原因。
您不能使用基本XDocument.Load()重载来做到这一点。您要么必须将内容作为字符串单独下载,要么至少获得具有正确标头的流并使用正确的重载。
XDocument GetSecureXDocument(string url)
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var client = new WebClient
{
Headers = { [HttpRequestHeader.Accept] = "application/xml" }
};
using (var stream = client.OpenRead(url))
return XDocument.Load(stream);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
780 次 |
| 最近记录: |