post到https的一个小坑

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了post到https的一个小坑相关的知识,希望对你有一定的参考价值。

  一个小坑,坑了我半天时间

本地用的是.net2.0,post按照正常的httpwebrequest方式写没有问题,但是发布到服务器上是.net4.0,于是开始报错“基础连接已关闭:发送时发生错误”。

做了几个修改,于是成功。

1、添加TLS

2、添加httpversion11

3、url改为IP地址(这个不确定有没有关系)

post方法如下:

///zhh
private string Post(string url, string json) { System.Net.HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest; System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;//关键修正 System.Net.ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); webRequest.Method = "POST"; webRequest.ContentType = "application/json;charset=UTF-8"; webRequest.ServicePoint.Expect100Continue = false; webRequest.ProtocolVersion = System.Net.HttpVersion.Version11;//关键修正 webRequest.Timeout = 20000; webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"; webRequest.KeepAlive = false; string responseData = null; try { using (Stream requestStream = webRequest.GetRequestStream()) { byte[] data = System.Text.Encoding.ASCII.GetBytes(json); requestStream.Write(data, 0, data.Length); } System.Net.HttpWebResponse response = webRequest.GetResponse() as System.Net.HttpWebResponse; using (Stream responseStrem = response.GetResponseStream()) { StreamReader responseReader = new StreamReader(responseStrem, System.Text.Encoding.UTF8); responseData = responseReader.ReadToEnd(); } } catch (Exception ex) { throw ex; } return responseData; } private bool CheckValidationResult(object sp, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain req, System.Net.Security.SslPolicyErrors sslError) { return true; }

  

以上是关于post到https的一个小坑的主要内容,如果未能解决你的问题,请参考以下文章

php的一个小坑,输出不了json_encode

discuz X3.1 源代码阅读,记录代码片段

flask 链接mysql数据库 小坑

这两个代码片段有啥区别?

mybatis使用常见小坑总结

gitlab clone with https 展示URL修改小坑