System.Net.WebException:“基础连接已经关闭: 发送时发生错误。”的解决方法

2021-03-19

System.Net.WebException:“基础连接已经关闭: 发送时发生错误。”的解决方法:

在:HttpWebRequestmyReq=(HttpWebRequest)WebRequest.Create(uri);前加入:

ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls12;

ServicePointManager.ServerCertificateValidationCallback=delegate{returntrue;};

ServicePointManager.CheckCertificateRevocationList=false;

ServicePointManager.DefaultConnectionLimit=512;

ServicePointManager.Expect100Continue=false;

如下:

privatestringGetHttpWebRequest(stringurl)

{

Uriuri=newUri(url);

ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls12;

ServicePointManager.ServerCertificateValidationCallback=delegate{returntrue;};

ServicePointManager.CheckCertificateRevocationList=false;

ServicePointManager.DefaultConnectionLimit=512;

ServicePointManager.Expect100Continue=false;

HttpWebRequestmyReq=(HttpWebRequest)WebRequest.Create(uri);

myReq.UserAgent="Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/84.0.4147.89Safari/537.36";

myReq.Accept="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";

myReq.KeepAlive=false;

myReq.Headers.Add("Accept-Language","zh-cn,en-us;q=0.5");

HttpWebResponseresult=(HttpWebResponse)myReq.GetResponse();

StreamreceviceStream=result.GetResponseStream();

StreamReaderreaderOfStream=newStreamReader(receviceStream,System.Text.Encoding.GetEncoding("utf-8"));

stringstrHTML=readerOfStream.ReadToEnd();

readerOfStream.Close();

receviceStream.Close();

result.Close();

returnstrHTML;

}


下一篇: System.Net.WebException:“基础连接已经关闭: 发送时发生错误。”的解决方法