我们有一些服务器运行 C# 控制台应用程序,该应用程序使用 HttpWebRequest 来获取一些数据。此数据是一个文本文件,无需凭据即可通过 HTTPS 访问。这些服务器使用的是 DHCP 保留 IP,但由于一些问题,我们不得不将它们更改为静态 IP。由于我们这样做了,我们注意到这些请求返回两个交替错误的频率可能比正常情况高出 100 倍(此数据每 5 分钟检索 8 个数据点,因此有相当数量的请求)。因此,大多数请求仍然有效,但比平时失败的请求更多。与使用静态 IP 相关的具体情况可能会导致我们如何制作此 HttpWebRequest 的问题?
错误
对 ID 为 1 的数据点发出 Web 请求时发生异常。说明:无法解析远程名称:'yourremoteserver.com';
对 ID 为 2 的数据点进行 Web 请求时发生异常。说明:操作已超时;
HttpWebRequest 代码
private Conditions MakeHTTPRequest()
{
currentStatusCode = "Not executed";
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://yourremoteserver.com/DataPoint1.TXT");
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.UserAgent = UserAgent; //UserAgent string retrieved from app.config file
request.CachePolicy = noCachePolicy;
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
if (request.Proxy != null)
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertificates);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader readStream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string fileString = readStream.ReadToEnd();
response.Close();
readStream.Close();
currentStatusCode = response.StatusCode.ToString();
Conditions conditions = GetAttributesFromText(fileString);
return conditions;
}
}
}
另外,还要注意一点,代理对象不会返回 null,但从来没有与之关联的地址。