摘要:[ASP.NET]HttpRequest使用SSL方式傳遞參數
當我們在使用HTTPRequest時原本都是只有使用80 Port,但如果要使用到443時該怎辦,所以只好上網搜尋了一下資料整理下面的code
如果有問題再請指教
string Result = string.Empty;
byte[] postbytes = Encoding.UTF8.GetBytes("ccc=1&httprequest=1");
try
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://xxx.happy.com");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = postbytes.Length;
//新增一個憑證(檔案完整位置,檔案密碼,密碼和金鑰的旗標)
X509Certificate2 cert1 = new X509Certificate2(System.AppDomain.CurrentDomain.BaseDirectory + "SSL\\sss.pfx", "qwerasdf!", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
myRequest.ClientCertificates.Add(cert1);
myRequest.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//設定驗證回呼(總是同意)
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
using (Stream reqStream = myRequest.GetRequestStream())
{
reqStream.Write(postbytes, 0, postbytes.Length);
}
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
using (Stream resStream = myResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(resStream, Encoding.UTF8))
{
Result = sr.ReadToEnd();
sr.Close();
}
}
}
myRequest.Abort();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
Response.Write(Result);