标签:res tran man enc call with static send header
最近一个推送信息的目标接口从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请求的示例
标签:res tran man enc call with static send header
原文地址:https://www.cnblogs.com/hamlin/p/10795100.html