c# - C# 中的 HTTPS POST 到证书错误的服务器 - 超时

标签 c# post ssl httpwebrequest webclient

我正在尝试在 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/

相关文章:

c# - 请求被中止 : Could not create SSL/TLS secure channel. |系统.Net.WebException

amazon-web-services - Websocket 通过 ELB 通过 SSL 连接到 Rabbitmq

c# - DataContractSerializer 不支持矩形数组

javascript - 无法使用 jquery.ajax 一致加载大型 json 响应

c# - 是否可以在 log4net 配置中使用通配符记录器名称?

php - 在 PHP 中发布数组

php - 如何阻止人们向 PHP API 发出大量请求?

security - JAVA - 我们可以忽略本地网络的 SSL 验证吗

c# - asp.net 中的 Web 服务 wsdl 中的默认值

c# - Roslyn:如何用表达式替换标识符名称