C# 利用HttpWebRequest进行HTTPS的post请求的示例

Posted hamlin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 利用HttpWebRequest进行HTTPS的post请求的示例相关的知识,希望对你有一定的参考价值。

最近一个推送信息的目标接口从http格式换成https格式,原来的请求无法正常发送,所以修改了发送请求的方法.标红的代码是新加了,改了之后就可以正常访问(不检测证书的)

 

public static string PostData3(string posturl, string postData, Encoding encoding)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;

byte[] data = encoding.GetBytes(postData);
// 准备请求...
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;
}
}

 

private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}

以上是关于C# 利用HttpWebRequest进行HTTPS的post请求的示例的主要内容,如果未能解决你的问题,请参考以下文章

C#利用HttpWebRequest进行post请求的示例(HTTPS)

C#利用HttpWebRequest进行post请求的示例(HTTPS)

C#利用HttpWebRequest进行post请求的示例(HTTPS)

C#中HttpWebRequest的用法详解

GJM : C# HttpWebRequest GET HTTP HTTPS 请求

在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求