HTTP 正常,HTTPS 在 GetRequestStream() 拋出「無法連接到遠程服務器」。已設置 ServerCertificateValidationCallback 返回 true。
https://112.74.109.190/tniol-api/pos/login,確認接口正常。ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
request.Host = "api.example.com"; // 真實域名
// .NET 4.5+ 自動支援 SNI
errors 參數決定是否接受。ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, errors) => true;
var request = (HttpWebRequest)WebRequest.Create("https://112.74.109.190/tniol-api/pos/login");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "api.example.com"; // 若有域名
using (var writer = new StreamWriter(request.GetRequestStream())) {
writer.Write("user_name=sapi&password=123");
}
using (var response = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream())) {
Console.WriteLine(reader.ReadToEnd());
}
強烈建議遷移至 HttpClient (.NET Core/5+ 原生,Framework 需 NuGet System.Net.Http):
var handler = new HttpClientHandler {
ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => true
};
using var client = new HttpClient(handler);
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair("user_name", "sapi"),
new KeyValuePair("password", "123")
});
var resp = await client.PostAsync("https://...", content);