C# 利用HttpWebRequest进行HTTPS的post请求的示例
2021-06-06 02:05
标签:res tran man enc call with static send header 最近一个推送信息的目标接口从http格式换成https格式,原来的请求无法正常发送,所以修改了发送请求的方法.标红的代码是新加了,改了之后就可以正常访问(不检测证书的) public static string PostData3(string posturl, string postData, Encoding encoding) byte[] data = encoding.GetBytes(postData); private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) C# 利用HttpWebRequest进行HTTPS的post请求的示例 标签:res tran man enc call with static send header 原文地址:https://www.cnblogs.com/hamlin/p/10795100.html
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
// 准备请求...
try
{
// 设置参数
if (posturl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(posturl) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else {
request = WebRequest.Create(posturl) as HttpWebRequest;
}
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
// request.TransferEncoding = encoding.HeaderName;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
string err = ex.Message;
LogHelper.Error("Post第三方地址" + posturl, ex);
return string.Empty;
}
}
{
return true;
}
下一篇:百度地图API获取数据
文章标题:C# 利用HttpWebRequest进行HTTPS的post请求的示例
文章链接:http://soscw.com/index.php/essay/91077.html