C#发送https请求有一点要注意:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest.ProtocolVersion = HttpVersion.Version10;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
否则会报错:未能建立安全的SSL/TLS通道
发送请求代码:
/// <summary> /// 发送请求(get/post/http/https) /// </summary> /// <param name="Uri">请求地址</param> /// <param name="JsonStr">json数据</param> /// <param name="Method">请求方式POST/GET</param> /// <returns></returns> public static string ClientRequest(string Uri, string JsonStr, string Method = "POST") { try { var httpRequest = (HttpWebRequest)HttpWebRequest.Create(Uri); httpRequest.Method = Method; httpRequest.ContentType = "application/json"; if (Method.ToLower() == "get") { httpRequest.ContentType = "application/x-www-form-urlencoded"; } httpRequest.Proxy = null; httpRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"; httpRequest.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.8,zh-hk;q=0.6,ja;q=0.4,zh;q=0.2"); httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; //如果是发送HTTPS请求 if (Uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); httpRequest.ProtocolVersion = HttpVersion.Version10; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; } else { ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } if (!string.IsNullOrEmpty(JsonStr)) { using (var dataStream = new StreamWriter(httpRequest.GetRequestStream())) { dataStream.Write(JsonStr); dataStream.Flush(); dataStream.Close(); } } var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); using (var dataStream = new StreamReader(httpResponse.GetResponseStream())) { var result = dataStream.ReadToEnd(); return result; } } catch (Exception ex) { return "{"error":"" + ex.Message + ""}"; } } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 }
//接收示例
Response.ContentType = "application/json";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
using (var reader = new System.IO.StreamReader(Request.InputStream))
{
string xmlData = reader.ReadToEnd();
if (!string.IsNullOrEmpty(xmlData))
{
//业务处理
JavaScriptSerializer jss = new JavaScriptSerializer();
PushModel model = jss.Deserialize(xmlData, typeof(PushModel)) as PushModel;
if (model != null)
{
channel_ids = model.channel_id;
msg = model.msg;
}
}
}
http://blog.csdn.net/lsm135/article/details/50367315