//回调验证证书问题
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// 总是接受
return true;
}
///<summary>
///采用https协议访问网络
///</summary>
///<param name="URL">url地址</param>
///<param name="strPostdata">发送的数据</param>
///<returns></returns>
public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)
{
// 这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
Encoding encoding = Encoding.Default;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); //创建证书文件
X509Certificate objx509 = new X509Certificate(@"D:\ExampleProject\pushIphone\pushIphone\cer\xx.pem","xxx"); //加载Cookie
request.CookieContainer = new CookieContainer(); //添加到请求里
request.ClientCertificates.Add(objx509);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
request.Method = "POST";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/x-www-form-urlencoded";
byte[] buffer = encoding.GetBytes(strPostdata);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
/***Send the data. **/
//Stream newStream = request.GetRequestStream();
//newStream.Write(buffer, 0, buffer.Length);[code=csharp]
//newStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
{
return reader.ReadToEnd();
}
}
[/code]
调用情况如下:string postData = "{\"aps\":{\"alert\":\"發送信息\",\"badge\":1,\"sound\":\"default\",\"when\":\"這是發生了什么?\"}}";string str = OpenReadWithHttps("https://gateway.sandbox.push.apple.com:2195", postData, "utf-8");
Response.Write(str);
Response.End();
出现错误如下:要求已經中止: 無法建立 SSL/TLS 的安全通道。
描述: 在執行目前 Web 要求的過程中發生未處理的例外情形。請檢閱堆疊追蹤以取得錯誤的詳細資訊,以及在程式碼中產生的位置。 例外詳細資訊: System.Net.WebException: 要求已經中止: 無法建立 SSL/TLS 的安全通道。原始程式錯誤:
行 80: byte[] buffer = encoding.GetBytes(strPostdata);
行 81: request.ContentLength = buffer.Length;
行 82: request.GetRequestStream().Write(buffer, 0, buffer.Length);
行 83: /***Send the data. **/
行 84: //Stream newStream = request.GetRequestStream();
//已执行了这句,不知道为什么还错~~~
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货