我收到此错误:{“基础连接已关闭:发送中发生意外错误。”}我尝试将ServicePointManage.SecurityProtocol
设置为不同的值,并且发现有些时候从服务器获得响应,有时没有。另外,但是我不确定为什么每次我收到错误时更改安全协议都会在下次运行应用程序以获取响应时有所帮助,所以我不确定问题是来自于我设置安全协议的方式还是来自服务器它本身也是我尝试从浏览器访问链接,并且一切正常,请查看我的代码并向我提出建议,所有与此职位相关的答案均无济于事。
private string getLocationIDfromGlassDoor(string location)
{
if (!string.IsNullOrEmpty(searchLocation))
{
System.Net.HttpWebRequest.DefaultWebProxy = null;
ServicePointManager.DefaultConnectionLimit = 20000000;
string url = "www.xxx.com";
Uri uri = new Uri(url, UriKind.Absolute);
System.Net.ServicePointManager.SecurityProtocol |=
SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Proxy = null;
request.Timeout = Timeout.Infinite;
request.KeepAlive = true;
request.Host = "www.xxx.co.uk";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0";
request.ContentType = "application/json;charset=UTF-8";
request.AutomaticDecompression = DecompressionMethods.GZip;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do your processings here....
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (String.IsNullOrWhiteSpace(response.CharacterSet))
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
//string data = readStream.ReadToEnd();
var data = ReadFully(receiveStream, 32000);
var doc = new HtmlDocument();
string result = System.Text.Encoding.UTF8.GetString(data);
doc.LoadHtml(result);
JObject json = JObject.Parse(result);
var locationId = (string)json.Descendants().OfType
<JProperty>
().First(a => a.Name == "id");
if (!string.IsNullOrEmpty(locationId))
{
readStream.Close();
receiveStream.Close();
return locationId;
}
else
{
errors.Add("Error");
return "";
}
}
}
}
catch(Exception e)
{
errors.Add(e.Message);
}
}
return "";
}
我还尝试将keepAlive设置为false。而且我也尝试了以下方法:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
我不确定我还缺少什么,以便每次我按预期发出请求时都能得到答复。