Loading

以Post方式向指定url地址发送数据并活得返回结果

 /// <summary>
        /// 以Post方式向指定url地址发送数据并活得返回结果
        /// </summary>
        /// <param name="wsUrl">目标url地址</param>
        /// <param name="data">需要发送的数据</param>
        /// <returns></returns>
        public static string PostData(string wsUrl, string data, CookieContainer cc)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(wsUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = cc;

            byte[] postDataBytes = Encoding.GetEncoding("GB2312").GetBytes(data);
            request.ContentLength = postDataBytes.Length;
            System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postDataBytes, 0, postDataBytes.Length);

            string result = string.Empty;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader readStream = new StreamReader(responseStream, Encoding.GetEncoding("GB2312")))
                    {
                        result = readStream.ReadToEnd();
                    }
                }
            }

            return result;
        }

        internal class TrustAllCertificatePolicy : ICertificatePolicy
        {
            public TrustAllCertificatePolicy()
            {
                // 
                // TODO: 在此处添加构造函数逻辑 
                // 
            }
            public bool CheckValidationResult(ServicePoint sp, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem)
            {
                return true;// 这是最关键的,返回true,告诉客户端忽略证书名称不匹配! 
            }
        }

 

posted @ 2012-06-18 17:51  The Mechanic  阅读(517)  评论(0编辑  收藏  举报