我们经常会写post请求将我们需要传递的参数传递给目标地址端口,最近在写PowerAutomate的http触发流时遇到了这个问题,我对PowerAutomate的触发器URL发送post请求,但没有成功,后端捕获的异常为”基础连接已关闭,发送时发生错误”。这个问题是于安全协议导致的,更换安全协议类型即可。
这个问题是由于安全协议导致的,更换安全协议类型即可。
可用代码如下:
usingSystem; usingSystem.IO; usingSystem.Net; usingSystem.Text; //传入目标地址Url和Post的参数jsonParas,返回目标端口的响应返回值publicstaticstringHttpRequestByPost(stringUrl, stringjsonParas) { //设置服务属性ServicePointManager.Expect100Continue=true; ServicePointManager.CheckCertificateRevocationList=true; ServicePointManager.DefaultConnectionLimit=100; ServicePointManager.SecurityProtocol= (SecurityProtocolType)3072;//这里设置了协议类型ServicePointManager.ServerCertificateValidationCallback=delegate { returntrue; }; //创建一个HTTP请求stringstrURL=Url; HttpWebRequestrequest= (HttpWebRequest)WebRequest.Create(strURL); request.Method="POST"; request.ContentType="application/json"; request.Accept="*/*"; byte[] payload; stringparaUrlCoded=jsonParas; payload=Encoding.UTF8.GetBytes(paraUrlCoded); request.ContentLength=payload.Length; //发送请求,获得请求流 Streamwriter; try { writer=request.GetRequestStream(); } catch (Exception) { writer=null; Console.Write("连接服务器失败!"); } writer.Write(payload, 0, payload.Length); writer.Close(); //获得返回值HttpWebResponseresponse; try { response= (HttpWebResponse)request.GetResponse(); } catch (WebExceptionex) { response=ex.ResponseasHttpWebResponse; } Streams=response.GetResponseStream(); StreamReadersRead=newStreamReader(s); stringpostContent=sRead.ReadToEnd(); sRead.Close(); returnpostContent; }
解决问题的核心代码是这段服务属性配置:
//设置服务属性ServicePointManager.Expect100Continue=true; ServicePointManager.CheckCertificateRevocationList=true; ServicePointManager.DefaultConnectionLimit=100; ServicePointManager.SecurityProtocol= (SecurityProtocolType)3072;//这里设置了协议类型ServicePointManager.ServerCertificateValidationCallback=delegate { returntrue; };
其中协议类型那一行,需要根据.Net的版本进行调整。
/*.net 4.0 设置:*/ServicePointManager.SecurityProtocol= (SecurityProtocolType)3072; /*.net 4.5 设置(只要写SecurityProtocolType能够点出来的属性就可以):*/ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls12||SecurityProtocolType.Ssl3||SecurityProtocolType.Tls11||SecurityProtocolType.Tls;