我正在尝试在 C# 中对未安装正确 SSL 证书的服务器(我的测试开发服务器)执行 HTTPS POST。使用 WebClient 和 HttpWebRequest 请求超时。我已经设置了自己的 ServerCertificateValidationCallback 来绕过证书检查,但这并没有帮助。如果我在网页中进行完全相同的调用,则调用成功。
所以:
Call to URL https://testServer/myAction?myData in webpage - succeeds.
POST to https://testServer/myAction with myData using WebClient - timeout.
我的 WebClient post 代码如下:
private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
//solve the problem of invalid certificates - accept all as valid
return true;
}
public void callPost(object o)
{
string myData = (string)o;
try
{
Uri uri = new Uri("https://testServer/myAction");
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
byte[] uploadBytes = Encoding.UTF8.GetBytes(myData);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
byte[] responseBytes = client.UploadData(uri, "POST", Encoding.UTF8.GetBytes(urlData));
Console.WriteLine("WebRequest:{0}\n", Encoding.ASCII.GetString(responseBytes));
}
catch (Exception e)
{
Console.WriteLine("WebRequest Error:{0}\n", e.ToString());
}
}
关于如何让 POST 在 C# 中工作的任何想法?谢谢!
最佳答案
经过更多的搜索,我发现有人遇到了类似的问题并且找到了解决方案。 要调试这种情况和类似情况,请按此处所述启用 SSL 跟踪/日志记录。 http://blogs.msdn.com/b/dgorti/archive/2005/09/18/471003.aspx
我的问题是我需要如下声明一个 SSL3 连接
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
在调用 client.UploadData
之前将其添加到我的代码中解决了这个问题。
关于c# - C# 中的 HTTPS POST 到证书错误的服务器 - 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18731285/