0
点赞
收藏
分享

微信扫一扫

C#———post请求http 或 https

王小沫 2022-02-25 阅读 179
c#
		public string Post(string PostUrl, string Parameters)
        {
            string content = string.Empty;
            try
            {
                //转换为字节数组
                byte[] bytesRequestData = Encoding.UTF8.GetBytes(Parameters.ToString());
                //path不是登录界面,是登录界面向服务器提交数据的界面
                
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(PostUrl);
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);	//https 请求必需语句 ,用来调过证书问题,http 请求可省略
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;	//https 请求必需语句,http 请求可省略
                myReq.Method = "post";	//设置调用方式
                myReq.ContentType = "text/xml; charset=utf-8";
                //myReq.Headers.Add("Username", "POD_JCK_ENTR");	//传统的用户名密码验证
                //myReq.Headers.Add("Password", "x!Q882uW11@b787");	//传统的用户名密码验证
                myReq.Headers.Add("Authorization", "Basic " + GetEncodedCredentials());	//https添加 Basic auth验证
                //myReq.Headers.Add("Authorization", "Basic UE9EX0pDS19FTlRSOnghUTg4MnVXMTFAYjc4Nw==");


                //填充POST数据
                myReq.ContentLength = bytesRequestData.Length;
                Stream requestStream = myReq.GetRequestStream();
                requestStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                requestStream.Close();
                //发送POST数据请求服务器
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                //获取服务器返回信息
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader reader = new StreamReader(myStream, Encoding.UTF8);
                content = reader.ReadToEnd();
                reader.Close();
                HttpWResp.Close();

            }
            catch (Exception ex)
            {
                content = ex.ToString();
            }

            return content;
        }

		private  bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受
        }
举报

相关推荐

0 条评论