- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.IO;
- using System.Security.Cryptography.X509Certificates;
- using System.Net.Security;
- namespace Simulator
- {
- class Simulator
- {
- public static string PostDataSSL(string purl, string str)
- {
- return PostData(purl, str, true);
- }
- public static string PostData(string url,string str){
- return PostData(url, str, false);
- }
- public static string PostData(string purl,string str,bool sslAuth)
- {
- //System.Net.WebRequest req = System.Net.WebRequest.Create("your url");
- //req.ContentType = "text/xml";
- //req.Method = "POST";
- //byte[] bytes = System.Text.Encoding.ASCII.GetBytes("Your Data");
- //req.ContentLength = bytes.Length;
- //os = req.GetRequestStream();
- //os.Write(bytes, 0, bytes.Length);
- //System.Net.WebResponse resp = req.GetResponse();
- //if (resp == null) return;
- //System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
- //str responsecontent = sr.ReadToEnd().Trim();
- //if (isCer)
- //{
- // //需要Https验证
- // System.Security.Cryptography.X509Certificates.X509Certificate cer;
- // //System.Security.Cryptography.X509Certificates.X509Certificate cer = System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(pfxPath);
- // if (String.IsNullOrEmpty(pfxPassword)) //是否证书加载是否需要密码
- // cer = new X509Certificate(pfxPath);
- // else
- // cer = new X509Certificate(pfxPath, pfxPassword);
- // webReq.ClientCertificates.Add(cer);
- //}
- try
- {
- byte[] data = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(str);
- // 准备请求
- HttpWebRequest req = (HttpWebRequest)WebRequest.Create(purl);
- if (sslAuth)
- {
- ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
- }
- //设置超时
- req.Timeout = 30000;
- req.Method = "POST";
- req.ContentType = "text/xml";
- req.ContentLength = data.Length;
- Stream stream = req.GetRequestStream();
-
- //req.ClientCertificates.Add(xCert);
- // 发送数据
- stream.Write(data, 0, data.Length);
- stream.Close();
- HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
- Stream receiveStream = rep.GetResponseStream();
- Encoding encode = System.Text.Encoding.GetEncoding("UTF-8");
- // Pipes the stream to a higher level stream reader with the required encoding format.
- StreamReader readStream = new StreamReader(receiveStream, encode);
- Char[] read = new Char[256];
- int count = readStream.Read(read, 0, 256);
- StringBuilder sb = new StringBuilder("");
- while (count > 0)
- {
- String readstr = new String(read, 0, count);
- sb.Append(readstr);
- count = readStream.Read(read, 0, 256);
- }
- rep.Close();
- readStream.Close();
- return sb.ToString();
- }
- catch (Exception ex)
- {
- return ex.Message;
- // ForumExceptions.Log(ex);
- }
- }
- }
- }
http和https的区分也有。
阅读(2627) | 评论(0) | 转发(0) |