最近一個項目中用到了https的請求,在實際調用過程中發現之前的http方法不支持https,調用一直報錯。 查詢了一下,添加幾行代碼解決問題。 public string HttpPost(string Url, string postDataStr, string useragent = nul ...
最近一個項目中用到了https的請求,在實際調用過程中發現之前的http方法不支持https,調用一直報錯。
查詢了一下,添加幾行代碼解決問題。
public string HttpPost(string Url, string postDataStr, string useragent = null)
{
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;//新增一行
System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;//新增第二行,很重要
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//新增第三行
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
if (!string.IsNullOrEmpty(useragent))
{
request.UserAgent = useragent;
}
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}