标签:
/// <summary> /// 提交数据请求 /// </summary> /// <param name="POSTURL">请求提交的地址 如:https://car.etaiping.com:6004/ecms2/portal/商户号/请求类型(接口名称) /// <param name="PostData">提交的数据(字符串)</param> /// <returns></returns> public string RequestData(string PostData) { string POSTURL = string.Format("https://www.sina.com.cn"); Encoding myEncoding = Encoding.GetEncoding("UTF-8"); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; //将提交的字符串数据转换成字节数组 //注意提交的编码,这里默认的是Default:系统当前编码 byte[] postData = myEncoding.GetBytes(PostData); //设置提交的相关参数 HttpWebRequest request = WebRequest.Create(POSTURL) as HttpWebRequest; //实例化一个证书 //X509Certificate2 cerCaiShang = GetCertificate(); ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; //request.ClientCertificates.Add(cerCaiShang); request.Method = "POST"; request.KeepAlive = true; //request.AllowAutoRedirect = true; request.ProtocolVersion = HttpVersion.Version10; request.ContentType = "text/xml;charset=utf-8"; //request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.ContentLength = postData.Length; //request.ClientCertificates.Add(new X509Certificate("C:\\CerPath\\_Cer.cer"));//证书路径 #region 传输数据 try { using (Stream writer = request.GetRequestStream()) { writer.Write(postData, 0, postData.Length); } } catch (Exception ex) { return ex.Message; } #endregion #region 接收返回的数据 string srcString = string.Empty; try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; using (Stream sr = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(sr, myEncoding)) { srcString = reader.ReadToEnd(); } } } catch (Exception ex) { return ex.Message; } #endregion return srcString; }
标签:
原文地址:http://www.cnblogs.com/XuPengLB/p/5724888.html