C#请求https的接口

在使用这个方法之前,保证framework的版本在4.0以上,经测试4.0的时候是不可以的,

重点在于加上以下代码

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = true;
ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; };

以下是完整的代码,伸手党,自己复制改动

  [HttpPost]
        public JsonResult CheckOrder(string messageNo)
        {
            string url = ConfigurationManager.AppSettings["queryAddress"].ToString();
            string keyid = ConfigurationManager.AppSettings["keyid"].ToString();
            Dictionary<string, string> myDictionary = new Dictionary<string, string>();
            myDictionary.Add("keyid", keyid);
            string postParaJsonStr = " { \"messageNo\":\"" + messageNo + "\" } ";
            string outResStr = "";
            bool res = HttpPost(url, myDictionary, postParaJsonStr, ref outResStr);
            string state = "";
            string errorinfo = "";
            if (res)
            {
                JToken jt = JsonConvert.DeserializeObject<JToken>(outResStr);
                state = jt["status"].ToString();
                errorinfo = jt["errorinfo"].ToString();

            }
            return Json(new { state = state, errorinfo = errorinfo });

        }
  public bool HttpPost(string Url, Dictionary<string, string> myDictionary, string postDataStr, ref string outResStr)
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls12;
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; };

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                request.KeepAlive = false;
                //request.ProtocolVersion = HttpVersion.Version10;
                //request.ContentType = "application/x-www-form-urlencoded";
                //request.Accept = "text/html, application/xhtml+xml, */*";
                //request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
                //request.AllowAutoRedirect = this._AllowAutoRedirect;
                //request.CookieContainer = new CookieContainer();
                //request.Referer = this._Referer;
                request.Timeout = 120000;
                //request.ReadWriteTimeout = 120000;
                //request.ServicePoint.Expect100Continue = true;
                //request.ServicePoint.ConnectionLimit = 1024;
                //request.KeepAlive = true; 

                foreach (var item in myDictionary)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
                Encoding encoding = Encoding.UTF8;
                byte[] postData = encoding.GetBytes(postDataStr);
                request.ContentLength = postData.Length;
                Stream myRequestStream = request.GetRequestStream();
                myRequestStream.Write(postData, 0, postData.Length);
                myRequestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);
                outResStr = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return true;
            }
            catch (Exception ex)
            {
                outResStr = ex.Message;
                return false;
            }

        }

简单粗暴的做个记录

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
要实现C#中的HTTPS接口调用,您可以遵循以下步骤: 1. 在项目中添加System.Net命名空间,这个命名空间提供了HTTP和HTTPS协议的类库。 2. 创建一个HttpWebRequest对象,用于请求HTTPS的URL地址。您可以使用WebRequest.Create方法来创建HttpWebRequest对象。 3. 配置HttpWebRequest对象的属性。例如,您需要设置请求的URL地址、请求方法、请求头等信息。您可以使用HttpWebRequest对象提供的相关属性来进行设置。 4. 向服务器发送请求并接收响应。您可以使用HttpWebRequest对象的GetResponse或者GetResponseStream方法来发送请求并接收响应。GetResponse方法将会阻塞当前线程,直到服务器返回响应。 5. 处理响应数据。您可以使用HttpWebResponse对象来获取响应数据,并将其转换为需要的格式(例如JSON或XML)。 下面是一个简单的C#代码示例,用于实现HTTPS接口调用: ```csharp using System; using System.IO; using System.Net; using System.Text; public class HttpsExample { public static void Main(string[] args) { // 创建HttpWebRequest对象 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://example.com/api"); // 配置HttpWebRequest对象的属性 request.Method = "POST"; request.ContentType = "application/json"; request.Headers.Add("Authorization", "Bearer your_access_token"); // 发送请求并接收响应 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); // 处理响应数据 StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); string responseText = reader.ReadToEnd(); Console.WriteLine(responseText); // 关闭响应流和HttpWebResponse对象 reader.Close(); responseStream.Close(); response.Close(); } } ``` 在实际开发中,您可能需要根据自己的需求进行更加复杂的HTTPS接口调用。但是,以上的步骤是基本的步骤,您可以根据这些步骤进行开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值