码迷,mamicode.com
首页 > Web开发 > 详细

post到https的一个小坑

时间:2017-04-12 11:35:07      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:user   pos   read   做了   bytes   cal   ascii   private   har   

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

本地用的是.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的一个小坑

标签:user   pos   read   做了   bytes   cal   ascii   private   har   

原文地址:http://www.cnblogs.com/cocomilk2015/p/6697959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!