一个小坑,坑了我半天时间
本地用的是.net2.0,post按照正常的httpwebrequest方式写没有问题,但是发布到服务器上是.net4.0,于是开始报错“基础连接已关闭:发送时发生错误”。
做了几个修改,于是成功。
1、添加TLS
2、添加httpversion11
3、url改为IP地址(这个不确定有没有关系)
post方法如下:
///zhhprivate 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; }
时间: 2024-10-16 17:39:40