HTTP请求PowerAutomate错误:”基础连接已关闭,发送时发生错误”

2024-02-03 10:25:37 浏览数 (1)

我们经常会写post请求将我们需要传递的参数传递给目标地址端口,最近在写PowerAutomate的http触发流时遇到了这个问题,我对PowerAutomate的触发器URL发送post请求,但没有成功,后端捕获的异常为”基础连接已关闭,发送时发生错误”。这个问题是于安全协议导致的,更换安全协议类型即可。

这个问题是由于安全协议导致的,更换安全协议类型即可。

可用代码如下:

代码语言:javascript复制
using System;
using System.IO;
using System.Net;
using System.Text;

//传入目标地址Url和Post的参数jsonParas,返回目标端口的响应返回值
public static string HttpRequestByPost(string Url, string jsonParas) {

  //设置服务属性
  ServicePointManager.Expect100Continue = true;
  ServicePointManager.CheckCertificateRevocationList = true;
  ServicePointManager.DefaultConnectionLimit = 100;
  ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;//这里设置了协议类型
  ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

  //创建一个HTTP请求
  string strURL = Url;
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
  request.Method = "POST";
  request.ContentType = "application/json";
  request.Accept = "*/*";
  byte[] payload;
  string paraUrlCoded = jsonParas;
  payload = Encoding.UTF8.GetBytes(paraUrlCoded);
  request.ContentLength = payload.Length;

  //发送请求,获得请求流 
  Stream writer;
  try {
    writer = request.GetRequestStream();
  }
  catch (Exception) {
    writer = null;
    Console.Write("连接服务器失败!");
  }
  writer.Write(payload, 0, payload.Length);
  writer.Close();

  //获得返回值
  HttpWebResponse response;
  try {
    response = (HttpWebResponse)request.GetResponse();
  }
  catch (WebException ex) {
    response = ex.Response as HttpWebResponse;
  }
  Stream s = response.GetResponseStream();
  StreamReader sRead = new StreamReader(s);
  string postContent = sRead.ReadToEnd();
  sRead.Close();
  return postContent;

}

解决问题的核心代码是这段服务属性配置:

代码语言:javascript复制
//设置服务属性
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 100;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;//这里设置了协议类型
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

其中协议类型那一行,需要根据.Net的版本进行调整。

代码语言:javascript复制
/*.net 4.0 设置:*/
 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
/*.net 4.5 设置(只要写SecurityProtocolType能够点出来的属性就可以):*/
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12|| SecurityProtocolType.Ssl3 || SecurityProtocolType.Tls11 || SecurityProtocolType.Tls;

Damon_Liu

Damon, Chinese, Liu Guangzhi, Software development engineer, CSDN quality creator, Ali Cloud expert blogger, Microsoft Technology Associate, Good at C#, Java, PHP, Python, etc, Love sports, Workaholic, Communist.

0 人点赞