1 public static string HttpPost(string url, string param = null)
2 {
3 HttpWebRequest request;
4
5 //如果是发送HTTPS请求
6 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
7 {
8 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; //协议按需选择,
9 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
10 request = WebRequest.Create(url) as HttpWebRequest;
11 request.ProtocolVersion = HttpVersion.Version10;
12
13 }
14 else
15 {
16 request = WebRequest.Create(url) as HttpWebRequest;
17 }
18
19 request.Method = "POST";
20 request.ContentType = "application/json";
21 request.Accept = "*/*";
22 request.Timeout = 15000;
23 request.AllowAutoRedirect = false;
24 //查找我们导入的证书
25 X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
26 certStore.Open(OpenFlags.ReadOnly);
27 var aa = certStore.Certificates;
28 X509Certificate2Collection certCollection = certStore.Certificates.Find(X509FindType.FindBySubjectName, "www.xxx.com", false);
29 request.ClientCertificates.Add(certCollection[0]);
30
31
32 StreamWriter requestStream = null;
33 WebResponse response = null;
34 string responseStr = null;
35
36 try
37 {
38 requestStream = new StreamWriter(request.GetRequestStream());
39 requestStream.Write(param);
40 requestStream.Close();
41
42 response = request.GetResponse();
43 if (response != null)
44 {
45 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
46 responseStr = reader.ReadToEnd();
47 reader.Close();
48 }
49 }
50 catch (Exception)
51 {
52 throw;
53 }
54 finally
55 {
56 request = null;
57 requestStream = null;
58 response = null;
59 }
60
61 return responseStr;
62 }
63
64
65 private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
66 {
67 return true; //总是接受
68 }