我正在尝试从 WEB API 加载 JSON 数据。如果我从任何浏览器请求数据,URL 工作正常。如果我尝试使用 webClient 获取数据,则相同的 URL 不起作用。它抛出以下错误:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +111
[IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +299
[WebException: The underlying connection was closed: An unexpected error occurred on a receive.]
System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +298
System.Net.WebClient.DownloadString(Uri address) +106
我发现这样可能会堆栈溢出类似的问题并实施 TSL 安全协议和标头更改,但仍然无法正常工作。
下面是我的代码:
PCR IWebClientServices<PCR>.PrepareWebClient(string PreparedURL)
{
try
{
//this code bypass the SSL exception
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls;
//now we will invoke the webClient
var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0");
var json = webClient.DownloadString(PreparedURL);
return JsonConvert.DeserializeObject<PCR>(json);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
我被困在这里,因为这段代码有时工作得很好,有时根本不起作用。我不知道出了什么问题,但我认为在请求浏览器请求等数据时我遗漏了一些东西,但服务器正在捕获一些可疑的请求并且没有响应。但是,如果我从浏览器浏览 URL,它会发送数据。